Python学习---django知识补充之CBV

Django知识补充之CBV

Django:

   url    -->  def函数      FBV[function based view]  用函数和URL进行匹配

   url    -->  类           CBV[function based view]  用类和URL进行匹配

POSTMAN插件

http://blog.csdn.net/zzy1078689276/article/details/77528249

 

基于CBV的登录实例:

settings.py

INSTALLED_APPS = [
   ...
 'app01',   # 注册app
]
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)  # 现添加的配置,这里是元组,注意逗号
TEMPLATES = [
   ...
   'DIRS': [os.path.join(BASE_DIR, 'templates')],
]

urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from app01 import views
urlpatterns = [
   # 基于CBV的登录
 # url(r'^login.html/', views.login),  # 原来基于函数
   url(r'^login.html/', views.Login.as_view()), # 现在基于类名.as_view()
]

views.py

from django.shortcuts import render, redirect
from app01 import models
# 基于CBV的登录,需要导入views
from django import views
class Login(views.View):
    # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    def get(self, request, *args, **kwargs):
        print(request.method, 'GGGGGGGGGGGG')
        message = ''
        return render(request, 'login.html', {'message': message})  # 这里是网页html
    def post(self, request, *args, **kwargs):
        print(request.method, 'OOOOOOOOOOOOO')
        username = request.POST.get("user")
        password = request.POST.get("pass")
        print('username: %s, password:%s' % (username, password))
         # obj = models.Administrator.objects.filter(username=username, password=password).count()
        # if obj:   从数据库内取出数据,进行判断也可以
        if username == 'root' and password == 'root':
            req = redirect('/index.html/')  # 接收redirect对象,# 这里是浏览器路径,伪静态
            # req.set_cookie('username', username, max_age=10)  # 设置超时时间10s
            import datetime
            timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
            req.set_cookie('username', username, max_age=10, expires=timeout)
            # IE设置超时时间10s
            return req
            # return redirect('/index.html') # 与上面3行同,只是添加了Cookie
        else:
            message = '用户名或密码错误'
            return render(request, 'login.html', {'message': message})  # 这里是网页html

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {# 伪静态#}
    <form action="/login.html/" method="post">
        {% csrf_token %}   {# 为跨站请求 #}
        <div>
            <label for="user">用户名</label>
            <input id="user" name="user" type="text">
        </div>
        <div>
            <label for="pass">密&nbsp;&nbsp;&nbsp;&nbsp;码</label>
            <input id="pass" name="pass" type="password">
        </div>
        <div>
            <label></label>
            <input value="登录" type="submit">
            <span style="color: red">{{ message }}</span>
        </div>
    </form>
</body>
</html>

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h2>hello, {{ username }}</h2>
</body>
</html>

页面显示:

image

 

CBV基于装饰器的使用<一>  ---基于Python旧方法

 

CBV基于装饰器的使用<一>  ---基于Python旧方法

装饰器:函数执行之前/后可以增加扩展功能

有多个方法的时候,必须给每个方法添加装饰器哈

CBV的反射原理

image

单一装饰器

views.py

from django.shortcuts import render, redirect
from app01 import models
# 基于CBV的登录,需要导入views
from django import views
from django.utils.decorators import method_decorator  # 导入装饰器
# 基于CBV的装饰器的使用
def outer(func):
    def inner(request, *args, **kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner

class Login(views.View):
    # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    @method_decorator(outer)
    def get(self, request, *args, **kwargs):
        message = ''
        return render(request, 'login.html', {'message': message})  # 这里是网页html

    @method_decorator(outer)
    def post(self, request, *args, **kwargs):
        username = request.POST.get("user")
        password = request.POST.get("pass")
        print('username: %s, password:%s' % (username, password))
        # obj = models.Administrator.objects.filter(username=username, password=password).count()
        # if obj:   从数据库内取出数据,进行判断也可以
        if username == 'root' and password == 'root':
            req = redirect('/index.html/')  # 接收redirect对象,# 这里是浏览器路径,伪静态
            # req.set_cookie('username', username, max_age=10)  # 设置超时时间10s
            import datetime
            timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
            req.set_cookie('username', username, max_age=10, expires=timeout)
            # IE设置超时时间10s
            return req
            # return redirect('/index.html') # 与上面3行同,只是添加了Cookie
        else:
            message = '用户名或密码错误'
            return render(request, 'login.html', {'message': message})  # 这里是网页html

CBV基于装饰器的使用<二>  --基于Django的dispatch[多个装饰器]

CBV基于装饰器的使用<二>  --基于Django的dispatch[多个装饰器]

如果对某一种请求做处理: 单一装饰器

如果对所有的请求做处理: dispatch单一装饰器

添加装饰器有2中方法:

    1.类上添加  

    2.方法上添加

image

自定义转发dispatch函数

from django import views
from django.utils.decorators import method_decorator  # 导入装饰器
class Login(views.View):
    # http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
    # 自定义转发器,URL进来都在此处进行URL转发,我们可以有一些预操作[函数验证可以放此处]
    def dispatch(self, request, *args, **kwargs):
        print('自定义dispatch: 前')
        # if request.method == 'POST':
            # return HttpResponse("Good Bye")    # 预操作处理
        # 请求先到Login的dispatch,然后调用父类的dispatch,返回结果给了obj
        obj = super(Login, self).dispatch(request, *args, **kwargs)  # 自定义转发且调用父类dispatch
        # 将父类的返回结果返回给界面,否则界面报错
        print('自定义dispatch: 后')
        return obj

    def get(self, request, *args, **kwargs):
        message = ''
        return render(request, 'login.html', {'message': message})  # 这里是网页html
        ...同上

image

posted @ 2018-08-01 20:48  小a玖拾柒  阅读(237)  评论(0编辑  收藏  举报