Django 查漏补缺

 

Django 查漏补缺

 

 

Django  内容回顾:

一、 Http 请求本质: 网络传输,运用socket

Django程序: socket 服务端

  a. 服务端监听IP和端口

  b. 浏览器发送请求

HTTP由两部分组成:请求和响应。当你在Web浏览器中输入一个URL时,浏览器将根据你的要求创建并发送请求,该请求包含所输入的URL以及一些与浏览器本身相关的信息。当服务器收到这个请求时将返回一个响应,该响应包括与该请求相关的信息以及位于指定URL(如果有的话)的数据。直到浏览器解析该响应并显示出网页(或其他资源)为止。
文件头解释

    1. GET 请求: "GET /index.html http1.1\r\nUser-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x6..\r\n\r\nAccept-Encoding:gzip\r\n\r\n"

          2. POST 请求: "POST /index.html http1.1\r\nUser-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x6..\r\n\r\nAccept-Encoding:gzip\r\n\r\nuser=cqz&hobby=lihao"

  c.  服务端接收请求

    1. 用 \r\n\r\n 来分开请求头和请求体;

    2. 用 \r\n 对信息进行再次分割请求头的内容;

    3. 用&符来分割请求体的键值对;

    4. 讲内容封装到 request.POST 或 request.GET 中。

  d. 服务端响应

    1. 响应头: location: www.baidu.com

    2. 响应体

  e. 客户端与服务端相继断开连接

注: COOKIE 存在于请求头和响应头中

 


 

 二、 Django 的生命周期

  wsgi    ->    中间件    ->    路由系统    ->    中间件    ->    视图函数(ORM, Template, 渲染)

  Django 框架是没有 socket 功能的,在本地测试的时候,主要由 wsgiref 来提供,后期将会时候更强大的版本  - uwsgi.

 


三、FBV和CBV

function based view : URL 对应函数

class based vied : URL 对应类

CBV 主要基于 dispath 和继承来使用, 可自定义一个类,然后继承 views limian de  View;

 

from django.views import View

class Login(View):
    def dispatch(self, request, *args, **kwargs):
        return super(Login, self).dispatch(request, *args, **kwargs)

    def get(self, request):
        return render(request, "user/login.html")

    def post(self, request):
        username = "always"
        password = "always123"
        if request.POST.get("username") == username and request.POST.get("password") == password:
            request.session['user'] = "always"
            return redirect("/")
        return render(request, "user/login.html")

  在这个类中,一共可以定义下面几种方法,在 restful 规范中,被赋予如下含义:

    get :获取;post : 创建;put:更新;patch:局部跟新; delete:删除; 等

   在类中重写 dispath 方法,相当于为这个方法创建了一个装饰器,当然,我们也可以手动为这个类,或其中的函数增加装饰器,装饰器通常有三个位置可以放置

1. get、post方法上

from django.views import View
from django.utils.decorators import method_decorator

class LoginView(View):
    
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView,self).dispatch(request, *args, **kwargs)

    def get(self,request):
        return render(request,'login.html')

    @method_decorator(test)
    def post(self,request):
        # request.GET
        # request.POST # 请求头中的:content-type
        # request.body
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex3714":
            # 生成随机字符串
            # 写浏览器cookie: session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user_info':'alex}
            # }
            request.session['user_info'] = "alex"
            return redirect('/index.html')
        return render(request, 'login.html')
在方法上加装饰器

 

2. dispath 方法上

from django.views import View
from django.utils.decorators import method_decorator

class LoginView(View):
    @method_decorator(test)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView,self).dispatch(request, *args, **kwargs)

    def get(self,request):
        return render(request,'login.html')

    
    def post(self,request):
        # request.GET
        # request.POST # 请求头中的:content-type
        # request.body
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex3714":
            # 生成随机字符串
            # 写浏览器cookie: session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user_info':'alex}
            # }
            request.session['user_info'] = "alex"
            return redirect('/index.html')
        return render(request, 'login.html')
在 dispath 方法上加装饰器

 

3. 类上

from django.views import View
from django.utils.decorators import method_decorator

@method_decorator(test,name='get')
class LoginView(View):
    
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView,self).dispatch(request, *args, **kwargs)

    def get(self,request):
        return render(request,'login.html')


    def post(self,request):
        # request.GET
        # request.POST # 请求头中的:content-type
        # request.body
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex3714":
            # 生成随机字符串
            # 写浏览器cookie: session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user_info':'alex}
            # }
            request.session['user_info'] = "alex"
            return redirect('/index.html')
        return render(request, 'login.html')
加在类上的装饰器

 

 

 注: CSRF Token 只能加到 dispath 上

from django.views import View
from django.utils.decorators import method_decorator

from django.views.decorators.csrf import csrf_exempt,csrf_protect
class LoginView(View):
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginView,self).dispatch(request, *args, **kwargs)

    def get(self,request):
        return render(request,'login.html')


    def post(self,request):
        # request.GET
        # request.POST # 请求头中的:content-type
        # request.body
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user == 'alex' and pwd == "alex3714":
            # 生成随机字符串
            # 写浏览器cookie: session_id: 随机字符串
            # 写到服务端session:
            # {
            #     "随机字符串": {'user_info':'alex}
            # }
            request.session['user_info'] = "alex"
            return redirect('/index.html')
        return render(request, 'login.html')
CSRF Token 加装饰器

 

 


 

 四、 中间件

  • 是一个轻量级、底层的插件系统,可以介入Django的请求和响应处理过程,修改Django的输入或输出
  • 激活:添加到Django配置文件中的MIDDLEWARE_CLASSES元组中
  • 每个中间件组件是一个独立的Python类,可以定义下面方法中的一个或多个
    • _init _:无需任何参数,服务器响应第一个请求的时候调用一次,用于确定是否启用当前中间件
    • process_request(request):执行视图之前被调用,在每个请求上调用,返回None或HttpResponse对象
    • process_view(request, view_func, view_args, view_kwargs):调用视图之前被调用,在每个请求上调用,返回None或HttpResponse对象
    • process_template_response(request, response):在视图刚好执行完毕之后被调用,在每个请求上调用,返回实现了render方法的响应对象
    • process_response(request, response):所有响应返回浏览器之前被调用,在每个请求上调用,返回HttpResponse对象
    • process_exception(request,response,exception):当视图抛出异常时调用,在每个请求上调用,返回一个HttpResponse对象
  • 使用中间件,可以干扰整个处理过程,每次请求中都会执行中间件的这个方法
  • 示例:自定义异常处理
  • 与settings.py同级目录下创建myexception.py文件,定义类MyException,实现process_exception方法
from django.http import HttpResponse
class MyException():
    def process_exception(request,response, exception):
        return HttpResponse(exception.message)
  • 将类MyException注册到settings.py中间件中
MIDDLEWARE_CLASSES = (
    'test1.myexception.MyException',
    ...
)

  使用中间件时候,应继承 MiddlewareMixin 这个类

from django.utils.deprecation import MiddlewareMixin

  当然,如果这个类不存在,可以自己写一个

class MiddlewareMixin:
    def __init__(self, get_response=None):
        self.get_response = get_response
        super().__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

  

 

posted on 2017-09-19 15:46  何必从头  阅读(195)  评论(0编辑  收藏  举报

导航