django restframework的简单使用
1.快速上手
- 配置: (pip install djangorestframework==3.12.4)
# settings.py
INSTALLED_APPS = [
'rest_framework'
]
REST_FRAMEWORK = {
# DRF的相关配置后面都在这里
}
- urls和views
# urls.py
from django.urls import path
from app01 import views
urlpatterns = [
path('api/user/', views.UserView.as_view()),
]
# views.py
from rest_framework.views import APIView
from rest_framwork.response import Response
class UserView(APIView):
def get(self, request, *args, **kwargs):
return Response({"code": 0, 'data': 'xxxx'})
def post(self, request, *args, **kwargs):
return Response({"code": 0, 'data': 'xxxx'})
2.drf相关
drf重写了as_view()和dispatch()方法. 添加了一些功能:
- as_view(继承了父类中as_view): 免除了csrf的验证. 一般前后端分离不使用csrf. 后期会使用jwt认证
- dispatch(没继承父类的dispatch): 内部添加了版本处理, 认证, 权限, 访问频率
3.drf对于请求数据的封装
reqeust的使用:
# views.py
from rest_framework.views import APIView
from rest_framwork.response import Response
class UserView(APIView):
def get(self, request, *args, **kwargs):
print(request._request.GET)
print(request._request.method) # 通过对象嵌套了找到原始的request
print(request._request.POST)
print(request.query_params) # 本质上就是request._reqeust.GET
print(request.data) # 读取请求体并处理, eg: 发来Json, 内部会将其反序列化
return Response({"code": 0, 'data': 'xxxx'})
def post(self, request, *args, **kwargs):
return Response({"code": 0, 'data': 'xxxx'})
标签:views,request,rest,django,restframework,简单,print,import,Response
From: https://www.cnblogs.com/Maxs-message/p/17324235.html