博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django 查漏补缺
阅读量:7116 次
发布时间:2019-06-28

本文共 7084 字,大约阅读时间需要 23 分钟。

 

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 Viewclass 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 Viewfrom django.utils.decorators import method_decoratorclass 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 Viewfrom django.utils.decorators import method_decoratorclass 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 Viewfrom 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 Viewfrom django.utils.decorators import method_decoratorfrom django.views.decorators.csrf import csrf_exempt,csrf_protectclass 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 HttpResponseclass 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

  

 

转载于:https://www.cnblogs.com/alwaysInMe/p/7545809.html

你可能感兴趣的文章
2012开源项目计划-WPF企业级应用整合平台
查看>>
边缘检测(3)Sobel边缘算子
查看>>
C语言字符串和数字转换函数大全
查看>>
InfluxDB删除数据
查看>>
开篇记录
查看>>
我的友情链接
查看>>
debian6 Redis+phpredis安装
查看>>
Google Auth+openssh
查看>>
NFS服务器配置及客户端挂载
查看>>
ELK(elasticsearch+logstash+kibana)开源日志分析平台搭建
查看>>
Debian 8.0桌面系统root用户登录和root用户自动登录
查看>>
Windows 8 新启动方式:混合启动(Hybrid Boot)
查看>>
cacti 安装
查看>>
Eclipse大括号换行显示
查看>>
*.manifest 文件
查看>>
要在jsp界面上显示一行三个控件
查看>>
我的linux学习之路-文件的创建于删除
查看>>
NFS-上课内容
查看>>
数字电子技术基础第一章随手笔记
查看>>
如何解决MySQL 服务正在启动 . MySQL 服务无法启动. 服务没有报告任何错误.的问题...
查看>>