Django-中间件,错误中间件

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

注:最新版本2.0以上使用path 或者re_path

4.中间件设置,增加booktest/MyException文件

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin

# 自定义异常处理
class MyException(MiddlewareMixin):
    def process_exception(request, response, exception):
        return HttpResponse('abc')

注:一定要传入MiddlewareMixin,否则编译不成功

5.设置setting配置的中间件’booktest.MyException.MyException’,

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'booktest.MyException.MyException',
]

Django-验证码

1.创建app

python manage.py startapp booktest

2.安装验证码库

# 安装验证码,图片包
pip install pillow

# 验证码库
pip install django-multi-captcha-admin django-simple-captcha

simple-captcha https://github.com/mbi/django-simple-captcha
recaptcha https://github.com/praekelt/django-recaptcha
recaptcha2 https://github.com/kbytesys/django-recaptcha2

 

3.setting添加booktest,同时添加验证码库multi_captcha_admin

INSTALLED_APPS = [
    'multi_captcha_admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'booktest',
]
# admin站点动态验证码
MULTI_CAPTCHA_ADMIN = {
    'engine': 'simple-captcha'
}

4. 验证码数据库迁移,否则显示不出来

python manage.py migrate

注:一定要迁移,admin才能显示验证码

5.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

6.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^verifyCode$', views.verifyCode),
    re_path(r'^verifyTest1', views.verifyTest1),
    re_path(r'^verifyTest2', views.verifyTest2),

]

注:最新版本2.0以上使用path 或者re_path

 

7.编写视图

# coding=utf-8

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# 验证码
def verifyCode(request):
    from PIL import Image, ImageDraw, ImageFont
    import random
    # 创建背景色
    bgColor = (random.randrange(50, 100), random.randrange(50, 100), 0)
    # 规定宽高
    width = 100
    height = 25
    # 创建画布
    image = Image.new('RGB', (width, height), bgColor)
    # 构造字体对象
    # font = ImageFont.truetype('FreeMono.ttf', 24)
    font = ImageFont.load_default().font
    # 创建画笔
    draw = ImageDraw.Draw(image)
    # 创建文本内容
    text = '0123ABCD'
    # 逐个绘制字符
    textTemp = ''
    for i in range(4):
        textTemp1 = text[random.randrange(0, len(text))]
        textTemp += textTemp1
        draw.text((i * 25, 0),
                  textTemp1,
                  (255, 255, 255),
                  font)
    request.session['code'] = textTemp
    # 保存到内存流中
    # import cStringIO
    # buf = cStringIO.StringIO()
    # image.save(buf, 'png')

    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    image.save(buf, 'png')
    # 将内存流中的内容输出到客户端
    return HttpResponse(buf.getvalue(), 'image/png')


def verifyTest1(request):
    return render(request, 'booktest/verifyTest1.html')


def verifyTest2(request):
    code1 = request.POST['code1']
    code2 = request.session['code']
    if code1 == code2:
        return HttpResponse("ok")
    else:
        return HttpResponse("no")


def verifyCode_方式1(request):
    from PIL import Image, ImageDraw, ImageFont
    # 引入随机函数模块
    import random
    # 定义变量,用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
        20, 100), 255)
    width = 100
    height = 25
    # 创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    # 创建画笔对象
    draw = ImageDraw.Draw(im)
    # 调用画笔的point()函数绘制噪点
    for i in range(0, 100):
        xy = (random.randrange(0, width), random.randrange(0, height))
        fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
        draw.point(xy, fill=fill)
    # 定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # 随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    # 构造字体对象,ubuntu的字体路径为“/usr/share/fonts/truetype/freefont”
    # font = ImageFont.truetype('FreeMono.ttf', 23)
    font = ImageFont.load_default().font
    # 构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    # 绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    # 释放画笔
    del draw
    # 存入session,用于做进一步验证
    request.session['verifycode'] = rand_str
    """
    python2的为
    # 内存文件操作
    import cStringIO
    buf = cStringIO.StringIO()
    """
    # 内存文件操作-->此方法为python3的
    import io
    buf = io.BytesIO()
    # 将图片保存在内存中,文件类型为png
    im.save(buf, 'png')
    # 将内存中的图片数据返回给客户端,MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

8.templates/booktest文件

verifyTest1

Django-html转义和csrf权限

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    re_path(r'^htmlTest$', views.htmlTest),
    re_path(r'^csrf1$', views.csrf1),
    re_path(r'^csrf2$', views.csrf2),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


# html转义
def htmlTest(request):
    context = {'t1': '<h1>123</h1>'}
    return render(request, 'booktest/htmlTest.html', context)


# csrf
def csrf1(request):
    return render(request, 'booktest/csrf1.html')


def csrf2(request):
    uname = request.POST['uname']
    return HttpResponse(uname)

6.templates/booktest文件

csrf1 htmlTest

Django-定于模板与模板继承

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^captcha/', include('captcha.urls')),
    path('blog/', include('blog.urls')),
    # path('booktest/', include('booktest.urls', 'booktest')),
    # 2.0以后,反向解析使用以下方式
    path('booktest/', include(('booktest.urls', 'booktest'), namespace='booktest')),
]

4.配置booktest/urls

from django.urls import path, re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path(r'^(\d+)/(\d+)$', views.show, name='show'),
    re_path(r'^index2$', views.index2, name='index2'),
    re_path(r'^user1', views.user1, name='user1'),
    re_path(r'^user2', views.user2, name='user2'),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import HttpResponse
from booktest.models import HeroInfo
import logging


def index(request):
    # hero = HeroInfo.objects.get(pk=1)
    # context = {'hero': hero}

    # logging.debug('调试: %s' % (hero.hname))
    list = HeroInfo.objects.filter(isDelete=False)
    context = {'list': list}
    return render(request, 'booktest/index.html', context)


def show(request, id, id2):
    context = {'id': id}
    return render(request, 'booktest/show.html', context)


# 用于练习模板的继承
def index2(request):
    return render(request, 'booktest/index2.html')


def user1(request):
    context = {'uname': '习总'}
    return render(request, 'booktest/user1.html', context)


def user2(request):
    return render(request, 'booktest/user2.html')


6.templates/booktest文件

base base_goods base_user index index2 show user1 user2

 

 

Django-session-redis

1.安装django-redis-sessions

pip install django-redis-sessions

注:前提的linux或win安装好redis服务端

2.配置setting文件

SESSION_ENGINE = ‘redis_sessions.session’
SESSION_REDIS_HOST = ‘localhost’
SESSION_REDIS_PORT = 6379
SESSION_REDIS_DB = 0
SESSION_REDIS_PASSWORD = ”
SESSION_REDIS_PREFIX = ‘session’

3.其他操作访问按上篇

django-session

4.查看redis

 

5.django存储的是base64方式,可解密

 

 

Django-session

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path, re_path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include('booktest.urls', 'booktest')),
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [

    path('session1/', views.session1),
    path('session2/', views.session2),
    path('session2_handle/', views.session2_handle),
    path('session3/', views.session3),

]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from booktest.models import BookInfo
import datetime
import logging



# 通过用户登录练习session
def session1(request):
    uname = request.session.get('myname', '未登录')
    context = {'uname': uname}
    return render(request, 'booktest/session1.html', context)


def session2(request):
    return render(request, 'booktest/session2.html')


# 提交保存session
def session2_handle(request):
    uname = request.POST['uname']
    # logging.debug('获取用户名: %s' % (uname))
    request.session['myname'] = uname
    request.session.set_expiry(0)
    return redirect('/booktest/session1/')


def session3(request):
    # 删除session
    del request.session['myname']
    return redirect('/booktest/session1/')

注:cookies写入把注释打开!

 

5.post的静态页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="/booktest/session2_handle/">
    {% csrf_token %}
    <input type="text" name="uname">
    <input type="submit" name="登录">
</form>
</body>
</html>

注:防注入一定要添加{% csrf_token %}

 

5.访问网址

http://127.0.0.1:8000/booktest/session1/

 

 

 

 

出自于:GerryBlog

Django-request、response、重定向

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    path('', views.index),
    path('<int:id>/', views.show),
    re_path(r'^detail/(?P<p1>[0-9]{4})/(?P<p2>[0-9]{2})/(?P<p3>[0-9]{2})/$', views.detail),
    path('getTest1/', views.getTest1),
    path('getTest2/', views.getTest2),
    path('getTest3/', views.getTest3),
    path('postTest1/', views.postTest1),
    path('postTest2/', views.postTest2),

    path('cookieTest/', views.cookieTest),

    path('redTest1/', views.redTest1),
    path('redTest2/', views.redTest2),
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path(r'^detail/(?P<p1>[0-9]{4})/(?P<p2>[0-9]{2})/(?P<p3>[0-9]{2})/$', views.detail)
]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from booktest.models import BookInfo
import datetime
import logging


# Create your views here.
def index(request):
    # return HttpResponse('Hello World!')
    # temp = loader.get_template('booktest/index.html')
    # return HttpResponse(temp.render())
    # bookList = BookInfo.objects.all()
    # nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    # BookInfo.books2.create('使用类对象方式创建', nowTime).save()
    bookList = BookInfo.books2.all()
    context = {'list': bookList}
    return render(request, 'booktest/index.html', context)


def show(request, id):
    book = BookInfo.books2.get(pk=id)
    herolist = book.heroinfo_set.all()
    context = {'list': herolist}
    return render(request, 'booktest/show.html', context)


def detail(request, p1, p2, p3):
    return HttpResponse('year:%s,month:%s,day:%s' % (p1, p2, p3))


def getTest1(request):
    # 根据键接收值
    # a1 = request.GET['a']
    # logging.debug('调试: %s' % (a1))
    return render(request, 'booktest/getTest1.html')


# 接收一键一值的情况
def getTest2(request):
    # 根据键接收值
    a1 = request.GET['a']
    b1 = request.GET['b']
    c1 = request.GET['c']
    # 构造上下文
    context = {'a': a1, 'b': b1, 'c': c1}
    # 向模板中传递上下文,并进行渲染
    return render(request, 'booktest/getTest2.html', context)


# 接收一键多值的情况
def getTest3(request):
    a1 = request.GET.getlist('a')
    context = {'a': a1}
    return render(request, 'booktest/getTest3.html', context)


def postTest1(request):
    return render(request, 'booktest/postTest1.html')


def postTest2(request):
    uname = request.POST['uname']
    upwd = request.POST['upwd']
    ugender = request.POST.get('ugender')
    uhobby = request.POST.getlist('uhobby')
    context = {'uname': uname, 'upwd': upwd, 'ugender': ugender, 'uhobby': uhobby}
    return render(request, 'booktest/postTest2.html', context)


# cookie练习
def cookieTest(request):
    response = HttpResponse()
    cookie = request.COOKIES
    # logging.debug('调试: %s' % (cookie))
    # py3不存在has_key方法,改一下方法
    if 't1' in cookie:
        # logging.debug('存在t1: %s' % (cookie['t1']))
        response.write(cookie['t1'])
    # response.set_cookie('t1', 'abc')
    return response


# 转向练习
def redTest1(request):
    # return HttpResponseRedirect('/booktest/redTest2/')
    return redirect('/booktest/redTest2/')


def redTest2(request):
    return HttpResponse('这是转向来的页面')

注:cookies写入把注释打开!

 

5.访问网址

http://127.0.0.1:8000/booktest/getTest1/

http://127.0.0.1:8000/booktest/postTest1/

http://127.0.0.1:8000/booktest/cookieTest/

http://127.0.0.1:8000/booktest/redTest1/

注:打开浏览器调试界面,查看Application/cookies

 

 

 

出自于:GerryBlog

Django-urls配置

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.配置跟目录的文件夹中的urls

from django.contrib import admin
from django.urls import path
from django.conf.urls import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('booktest/', include('booktest.urls'))
]

4.配置booktest/urls

from django.urls import path , re_path
from . import views

urlpatterns = [
    path('', views.index),
    re_path(r'^detail/(?P<p1>[0-9]{4})/(?P<p2>[0-9]{2})/(?P<p3>[0-9]{2})/$', views.detail)
]

注:最新版本2.0以上使用path 或者re_path

 

5.编写视图

from django.shortcuts import render
from django.http import *
from django.template import RequestContext, loader


# Create your views here.
def index(request):
    return HttpResponse('Hello World!')

def detail(request, p1, p2, p3):
    return HttpResponse('year:%s,month:%s,day:%s' % (p1, p2, p3))


5.访问网址

http://127.0.0.1:8000/booktest/

http://127.0.0.1:8000/booktest/detail/2018/06/04/

 

6.定义404错误文件,在templates目录下增加404.html文件

注:setting文件配置需要修改为调试模式

DEBUG = False

# 允许外网访问
ALLOWED_HOSTS = ['*']

 

出自于:GerryBlog

Django model filter 条件过滤

1.条件选取querySet的时候,filter表示=,exclude表示!=。
querySet.distinct() 去重复
__exact 精确等于 like ‘aaa’
__iexact 精确等于 忽略大小写 ilike ‘aaa’
__contains 包含 like ‘%aaa%’
__icontains 包含 忽略大小写 ilike ‘%aaa%’,但是对于sqlite来说,contains的作用效果等同于icontains。
__gt 大于
__gte 大于等于
__lt 小于
__lte 小于等于
__in 存在于一个list范围内
__startswith 以…开头
__istartswith 以…开头 忽略大小写
__endswith 以…结尾
__iendswith 以…结尾,忽略大小写
__range 在…范围内
__year 日期字段的年份
__month 日期字段的月份
__day 日期字段的日
__isnull=True/False

例子:
>> q1 = Entry.objects.filter(headline__startswith=”What”)
>> q2 = q1.exclude(pub_date__gte=datetime.date.today())
>> q3 = q1.filter(pub_date__gte=datetime.date.today())
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains=”food”)

即q1.filter(pub_date__gte=datetime.date.today())表示为时间>=now,q1.exclude(pub_date__gte=datetime.date.today())表示为<=now

 

2.booktest/views查询例子

# coding=utf-8
from django.shortcuts import render
from django.db.models import Max, F, Q
from booktest.models import BookInfo


def index(request):
    # list=BookInfo.books1.filter(heroinfo__hcontent__contains='六')
    # list=BookInfo.books1.filter(pk__lte=3)
    # Max1=BookInfo.books1.aggregate(Max('bpub_date'))
    # list=BookInfo.books1.filter(bread__gt=F('bcommet'))
    # list=BookInfo.books1.filter(pk__lt=4,btitle__contains='1')
    # list=BookInfo.books1.filter(pk__lt=4).filter(btitle__contains='1')
    list = BookInfo.books1.filter(Q(pk__lt=4) | Q(btitle__contains='1'))
    context = {'list1': list
               # ,'Max1':Max1
               }
    return render(request, 'booktest/index.html', context)

 

Django模型自定义管理器

1.创建app

python manage.py startapp booktest

2.setting添加booktest

3.编写booktest/models.py

 

from django.db import models


class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date')
    bread = models.IntegerField(default=0)
    bcommet = models.IntegerField(null=False)
    isDelete = models.BooleanField(default=False)

    class Meta:
        db_table = 'bookinfo'


class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField(default=True)
    hcontent = models.CharField(max_length=1000)
    isDelete = models.BooleanField(default=False)
    book = models.ForeignKey(BookInfo, null=True, blank=True, on_delete=models.SET_NULL)

4.数据迁移

python manage.py makemigrations
python manage.py migrate

 

5.编写模型管理类

from django.db import models


class BookInfoManager(models.Manager):
    def get_queryset(self):
        # return super(BookInfoManager, self).get_queryset().filter(isDelete=False)
        return super().get_queryset().filter(isDelete=False)

    def create(self, btitle, bpub_date):
        b = BookInfo()
        b.btitle = btitle
        b.bpub_date = bpub_date
        b.bread = 0
        b.bcommet = 1
        b.isDelete = False
        return b


class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)
    bpub_date = models.DateTimeField(db_column='pub_date')
    bread = models.IntegerField(default=0)
    bcommet = models.IntegerField(null=False)
    isDelete = models.BooleanField(default=False)

    class Meta:
        db_table = 'bookinfo'

    books1 = models.Manager()
    books2 = BookInfoManager()

    @classmethod
    def create(cls, btitle, bpub_date):
        b = BookInfo()
        b.btitle = btitle
        b.bpub_date = bpub_date
        b.bread = 0
        b.bcommet = 1
        b.isDelete = False
        return b


class HeroInfo(models.Model):
    hname = models.CharField(max_length=10)
    hgender = models.BooleanField(default=True)
    hcontent = models.CharField(max_length=1000)
    isDelete = models.BooleanField(default=False)
    book = models.ForeignKey(BookInfo, null=True, blank=True, on_delete=models.SET_NULL)

注:两种创建方式,推荐在BookInfoManager写create方法。

 

6.booktest/views.py测试增加数据

from django.shortcuts import render
from django.http import *
from django.template import RequestContext, loader
from booktest.models import BookInfo
import datetime


# Create your views here.
def index(request):
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    BookInfo.books2.create('使用类对象方式创建', nowTime).save()
    bookList = BookInfo.books2.all()
    context = {'list': bookList}
    return render(request, 'booktest/index.html', context)