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
Django 查漏补缺的更多相关文章
- 《CSS权威指南》基础复习+查漏补缺
前几天被朋友问到几个CSS问题,讲道理么,接触CSS是从大一开始的,也算有3年半了,总是觉得自己对css算是熟悉的了.然而还是被几个问题弄的"一脸懵逼"... 然后又是刚入职新公司 ...
- js基础查漏补缺(更新)
js基础查漏补缺: 1. NaN != NaN: 复制数组可以用slice: 数组的sort.reverse等方法都会改变自身: Map是一组键值对的结构,Set是key的集合: Array.Map. ...
- Entity Framework 查漏补缺 (一)
明确EF建立的数据库和对象之间的关系 EF也是一种ORM技术框架, 将对象模型和关系型数据库的数据结构对应起来,开发人员不在利用sql去操作数据相关结构和数据.以下是EF建立的数据库和对象之间关系 关 ...
- 2019Java查漏补缺(一)
看到一个总结的知识: 感觉很全面的知识梳理,自己在github上总结了计算机网络笔记就很累了,猜想思维导图的方式一定花费了作者很大的精力,特共享出来.原文:java基础思维导图 自己学习的查漏补缺如下 ...
- 20165223 week1测试查漏补缺
week1查漏补缺 经过第一周的学习后,在蓝墨云班课上做了一套31道题的小测试,下面是对测试题中遇到的错误的分析和总结: 一.背记题 不属于Java后继技术的是? Ptyhon Java后继技术有? ...
- 今天開始慢下脚步,開始ios技术知识的查漏补缺。
从2014.6.30 開始工作算起. 如今已经是第416天了.不止不觉.时间过的真快. 通过对之前工作的总结.发现,你的知识面.会决定你面对问题时的态度.过程和结果. 简单来讲.知识面拓展了,你才干有 ...
- Mysql查漏补缺笔记
目录 查漏补缺笔记2019/05/19 文件格式后缀 丢失修改,脏读,不可重复读 超键,候选键,主键 构S(Stmcture)/完整性I(Integrity)/数据操纵M(Malippulation) ...
- 【spring源码分析】IOC容器初始化——查漏补缺(四)
前言:在前几篇查漏补缺中,其实我们已经涉及到bean生命周期了,本篇内容进行详细分析. 首先看bean实例化过程: 分析: bean实例化开始后 注入对象属性后(前面IOC初始化十几篇文章). 检查激 ...
- Mysql查漏补缺
Mysql查漏补缺 存储引擎 数据库使用存储引擎来进行CRUD的操作,不同的存储引擎提供了不同的功能.Mysql支持的存储引擎有InnoDB.MyISAM.Memory.Merge.Archive.F ...
随机推荐
- 【sql】leetcode习题 (共 42 题)
[175]Combine Two Tables (2018年11月23日,开始集中review基础) Table: Person +-------------+---------+ | Column ...
- DOM0级事件绑定之js的onclick事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- JavaScript 中 reduce去重方法
过去有很长一段时间,我一直很难理解 reduce() 这个方法的具体用法,平时也很少用到它.事实上,如果你能真正了解它的话,其实在很多地方我们都可以用得上,那么今天我们就来简单聊聊 JS 中 redu ...
- Collections 工具类常见方法
Collections 工具类常用方法: 排序 查找,替换操作 同步控制(不推荐,需要线程安全的集合类型时请考虑使用 JUC 包下的并发集合) 排序操作 void reverse(List list) ...
- [NOIP模拟测试3] 建造游乐园 题解(欧拉图性质)
Orz 出题人石二队爷 我们可以先求出有n个点的联通欧拉图数量,然后使它删或增一条边得到我们要求的方案 也就是让它乘上$C_n^2$ (n个点里选2个点,要么删边要么连边,选择唯一) 那么接下来就是求 ...
- STM32嵌入式开发学习笔记(六):串口通信(上)
本文我们将了解STM32与外部设备通过串口通信的方式. 所谓串口通信,其实是一个类似于计算机网络的概念,它有物理层,比如规定用什么线通信,几伏特算高电平,几伏特算低电平.传输层,通信前要发RTS,CT ...
- error C2065: CoInitializeEx' : undeclared identifier 解决方法
错误: error C2065: CoInitializeEx' : undeclared identifier 解决方法 原因: 本来程序的编译选项选择的是:使用标准windows库,当改为在静态库 ...
- 使用并行ssh提高工作效率
我们经常需要ssh到多个主机上执行相同的命令,为了提高效率,我们通常会自己写个脚本,循环遍历执行我们的命令,比如: for host in `cat hosts.txt`;do ssh usernam ...
- Mina(一)
配置log4j注意事项: Log4J 1.2 users: slf4j-api.jar, slf4j-log4j12.jar, and Log4J 1.2.x slf4j-log4j*.jar要对应 ...
- artTemplate性能卓越的 js 模板引擎
artTemplate-3.0 新一代 javascript 模板引擎 目录 特性 快速上手 模板语法 下载 方法 NodeJS 使用预编译 更新日志 授权协议 特性 性能卓越,执行速度通常是 Mus ...