django
视图
django 函数视图与类视图
- FBV: function base view
- CBV: class baes view 基于反射原理根据请求方法处理不同,执行不同的函数
类视图原理:
a. 路由 url -> view() -> dispatch()反射原理实现执行不同的方法
函数视图与类视图代码对比:
# 函数视图def user(request):return HttpResponse('hello world')# 类视图from django.views import Viewclass StudentView(View):def get(self,request, *args, **kwargs):return HttpResponse('hello view get')def post(self,request, *args, **kwargs):return HttpResponse('hello view post')def put(self,request, *args, **kwargs):return HttpResponse('hello view put')
中间件
middleware

- 所有中间件
- process_reqeust
- process_view
- process_response
- process_exception
- process_renader_template
- 中间件的应用场景
- 权限
- 用户登录
- csrftoken
django的csrf是如何实现的?
使用 process_view 方法实现,因为需要检查视图函数是否有使用装饰器@csrf_exempt,去请求体或者cookie中获取token
django中CSRF配置,支持两种方式(基于函数视图)
全站启用CSRF,指定视图不启用
# settings.py -> MIDDLEWARE# 'django.middleware.csrf.CsrfViewMiddleware'from django.views.decorators.csrf import csrf_exempt@csrf_exemptdef index(request):return HttpResponse('hello index')
全站禁用CSRF,指定视图启用
from django.views.decorators.csrf import csrf_protectdef users(reqeust):user_list = ['wang', 'li']return HttpResponse(json.dumps({user_list}))
在类视图中使用
CSRF,基于装饰器装饰类方法
- 装饰类本身
from django.utils.decorators import method_decorator# 方法1class StudentView(View):@method_decorator(csrf_exempt)def dispatch(self, request, *args, **kwargs):return super().dispatch(request, *args, **kwargs)def get(self, request, *args, **kwargs):return HttpResponse('GET')def post(self, request, *args, **kwargs):return HttpResponse('POST')# 方法2@method_decorator(csrf_exempt, name='dispatch')class StudentView(View):def dispatch(self, request, *args, **kwargs):return super().dispatch(request, *args, **kwargs)def get(self, request, *args, **kwargs):return HttpResponse('GET')def post(self, request, *args, **kwargs):return HttpResponse('POST')
RESTful API规范
API与用户的通信协议,问题使用HTTPS协议
域名
- https://api.example.com 尽量将API部署在专用域名(会存在跨域问题)
- https://example.org/api API很简单
版本
URL,如 https://api.example.com/v1/
- 请求头跨域时,引发发送多次请求
路径,视网络上任何东西都是资源,均使用名词表示(可复数)
method
GET
POST 创建一个资源
- PUT更新资源(客户端提供改变后的完整资源)
- PATCH更新资源(客户端提供改变的属性)
- DELETE
过滤,通过在url上传参的形式传递搜索条件
- 状态码 参考http://www.rfcreader.com/#rfc2616_line2628
200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)204 NO CONTENT - [DELETE]:用户删除数据成功。400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。
- 错误处理,状态码是4xx时,应返回错误信息,使用error做key;{error: “Invalid API key”}
- 返回结果,针对不同操作,服务器向用户返回的结果应该符合以下规范
GET /collection:返回资源对象的列表(数组)GET /collection/resource:返回单个资源对象POST /collection:返回新生成的资源对象PUT /collection/resource:返回完整的资源对象PATCH /collection/resource:返回完整的资源对象DELETE /collection/resource:返回一个空文档
- Hypermedia API,RESTful API最好做到Hypermedia,即返回结果中提供链接,连向其他API方法,使得用户不查文档,也知道下一步应该做什么。
[{id:1,name: 'iphone',url: http://xxx.cn/1,},{id:2,name: 'xiaomi',url: http://xxx.cn/2,},]
摘自:http://www.ruanyifeng.com/blog/2014/05/restful_api.html
django rest framework
01 了解
DRF基本介绍
from django.views import View # djangofrom rest_framework.views import APIView # djangorestframeworkfrom rest_framework.authentication import BasicAuthenticationfrom rest_framework import exceptionsclass MyAuthenticataoin:"""自定义认证类"""def authenticate(self, request):token = request._request.GET.get('token')# 可以操作# 获取用户名# 数据库验证用户if not token:raise exceptions.AuthenticationFailed('用户认证失败')# 第一个参数:'wangdachui' 用户,绑定到request.userreturn ('wangdachui', None)def authenticate_header(self, val):passclass DogView(APIView):authentication_classes = [MyAuthenticataoin,]def get(self, request, *args, **kwargs):print(request)# <rest_framework.request.Request object at 0x0455C950>ret = {'code':1000,'msg':'xxx',}return HttpResponse(json.dumps(ret), status=201)def post(self, request, *args, **kwargs):passdef put(self, request, *args, **kwargs):pass
