AI-restful接口写法
restful接口规范
http协议请求方式:GET POST DELETE PUT PATCH OPTION HEAD
设计接口时必须使用这种格式的数据
GET 查看数据 book/1 ----->查看单条数据 {}
GET 查看数据 books-------->返回数据列表 [{},{},{}]
POST 提交数据添加到数据库 --------->返回添加数据 {}
PUT 更新 pk=1的数据 ------>返回更新后的数据 {}
PATCH 更新所有的数据
OPTION
HEAD 返回请求方式 比如 GET POST等
不使用DRF,来写接口
对于我们后台人员,写好接口把数据传给前端就okay了!
#url
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^course/', views.Courseview.as_view()),
]
#views.py
from django.shortcuts import render,HttpResponse
from django.views import View
# Create your views here.
from app01.models import *
import json
class Courseview(View):
def get(self,request):
ret=[] #get的接收方式为[{},{},{}]
course_list = Course.objects.all()
for course in course_list:
ret.append([
{"course_name": course.title},
{"course_desc":course.desc},
])
return HttpResponse(json.dumps(ret,ensure_ascii=False))
#也可以不使用json格式,效果一样,如下:
#return HttpResponse(ret)
#mdoels.py
from django.db import models # Create your models here.
class Course(models.Model):
title=models.CharField(max_length=32)
desc=models.CharField(max_length=32)
前端接收:
[[{"course_name": "羊肚儿"}, {"course_desc": "煮10秒钟,贼香"}], [{"course_name": "宽粉"}, {"course_desc": "两盘儿,配上我妈给我调的料"}]]
DRF
(1) APIView (*****)
(2) 序列化组件(*****)
(3) 视图类(mixin)(*****)
(4) 认证组件
(5) 权限组件
(6) 频率组件
(7) 分页组件
(8) 解析器组件(*****)
(9) 响应器组件
(10) url控制器
使用DRF,做数据接口--APIView(*****)
#views.py
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
# Create your views here.
from app01.models import *
import json class Courseview(APIView):
def get(self,request):
ret=[]
course_list = Course.objects.all()
for course in course_list:
ret.append([
{"course_name": course.title},
{"course_desc":course.desc},
])
return HttpResponse(json.dumps(ret,ensure_ascii=False))
APIView源码解析
相比于View类,增加了“重装request方法”,“认证、权限、频率”等,本质功能还是做分发!!
下边代码可以不看,知道View源码即可,只是在View的dispatch方法里增加了认证、权限、频率等组件而已!
#1.开始 urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^course/', views.Courseview.as_view()),
] #2.在Courseview的父类APIView中找as_view方法
class APIView(View):
schema = DefaultSchema() @classmethod
def as_view(cls, **initkwargs): #在APIView父类中找as_view方法
view = super(APIView, cls).as_view(**initkwargs)
view.cls = cls
view.initkwargs = initkwargs #3.在APIView父类中找as_view方法
class View(object): http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'] @classonlymethod
def as_view(cls, **initkwargs): def view(request, *args, **kwargs):
self = cls(**initkwargs) #self即Courseview实例化对象
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
self.request = request
self.args = args
self.kwargs = kwargs
return self.dispatch(request, *args, **kwargs) 在Courseview中找dispatch方法
view.view_class = cls return view 返回了view,当收到请求时,执行view()方法 #4.在Courseview中找dispatch方法,没有就在父类中找class Courseview(APIView):
def get(self,request):
ret=[]
course_list = Course.objects.all()
for course in course_list:
ret.append([
{"course_name": course.title},
{"course_desc":course.desc},
])
return HttpResponse(json.dumps(ret,ensure_ascii=False)) #5.APIView中的dispatch方法
def dispatch(self, request, *args, **kwargs):
self.args = args
self.kwargs = kwargs
#重装一个新的request对象
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate? try:
#认证
self.initial(request, *args, **kwargs) # Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc:
response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response
解析器组件(*****)
本质:基于http协议的数据编码格式 解析器中,两种数据编码格式: a,urlencoded b,json 这两种数据编码格式的区别在于:
urlencoded格式的数据,django会默认解析成{xx:oo,xx:ooo}格式;而json格式,django不会解析成固定格式,得自己解析
a.urlencoding
#url.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.Loginview.as_view()),
]
#views.py
from django.shortcuts import render,HttpResponse
from django.views import View
# Create your views here.
class Loginview(View):
def get(self,request):
return render(request,"login.html") def post(self,request):
print(request.body) #请求体重的原生数据
#b'csrfmiddlewaretoken=eZ95jvkSlvVeB9lTkK85EYvgID5iMu171WyV421cEXVGXsxmj6BlCRxzLfKQf6zJ&user=zhang&pwd=111'
print(request.post) #djanog会默认解析urlencoded格式的数据
#<QueryDict: {'csrfmiddlewaretoken': ['eZ95jvkSlvVeB9lTkK85EYvgID5iMu171WyV421cEXVGXsxmj6BlCRxzLfKQf6zJ'], 'user': ['zhang'], 'pwd': ['111']}>
return HttpResponse("ddd")
{## login.html#}
<form action="" method="post" enctype="application/x-www-form-urlencoded"> #默认解析格式为application/urlencoded
{% csrf_token %}
用户名:<input type="text" name="user">
密码:<input type="password" name="pwd">
<button type="submit">提交</button>
</form>
提交用户信息后
页面-检查-内容
#Request.HEADER
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh,zh-CN;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 105
Content-Type: application/x-www-form-urlencoded 数据编码格式
Cookie: csrftoken=WyCTGzykwCoTLvAm7XBwGbxPLIXPwOpS5WwxOUrXqAbfeWsSwmi8gTXOZ85ctcvm
Host: 127.0.0.1:8011
Origin: http://127.0.0.1:8011
Pragma: no-cache
Referer: http://127.0.0.1:8011/login/
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Mobile Safari/537.36 #Form Data 接收到的数据格式是“application/x-www-form-urlencoded” ,格式为:使用“&”符号,将信息连接起来
csrfmiddlewaretoken=nFrqVKA7F5p8iJCGkcfqI5wE0O9KipzZw3l435tKz3cuLaucJBW2iNWDeeh7fNFt&user=dudu&pwd=12332 #View Parsered django将接收到的格式转化为?????格式 格式为xxx:ooo
csrfmiddlewaretoken: nFrqVKA7F5p8iJCGkcfqI5wE0O9KipzZw3l435tKz3cuLaucJBW2iNWDeeh7fNFt
user: dudu
pwd: 123321
b.json
#login.html <button class="btn">Ajax</button>
<script>
$(".btn").click(function () {
$.ajax({
url:"",
type:"post",
contentType:"json",
data:JSON.stringify({
user:"dudu",
pwd:""
}),
success:function (data) {
console.log(data)
}
})
})
</script>
#views.py from django.shortcuts import render,HttpResponse
from django.views import View
# Create your views here.
class Loginview(View):
def get(self,request):
return render(request,"login.html") def post(self,request): import json
print(request.body) # 请求体中的原生数据
#b'{"user":"dudu","pwd":"555"}'
print(request.POST) #django默认不会对你的数据进行解析
#<QueryDict: {}>
# import json
print(json.loads(request.body.decode("utf8"))) #自己解析数据
#{'user': 'dudu', 'pwd': '555'}
print(json.loads(request.body.decode("utf8"))["user"]) print(type(request))
from django.core.handlers.wsgi import WSGIRequest return HttpResponse("POST")
DRF编码格式
from django.shortcuts import render,HttpResponse
from django.views import View
from rest_framework.views import APIView
# Create your views here.
from app01.models import *
import json class Courseview(APIView): #从APIViewrest_framework.views中导入
def get(self,request):
ret=[]
course_list = Course.objects.all()
for course in course_list:
ret.append([
{"course_name": course.title},
{"course_desc":course.desc},
])
return HttpResponse(json.dumps(ret,ensure_ascii=False)) def post(self,request):
print(request.data) #这个request是APIView中重新建立的request,
#相比于View的request,多了一个request.data方法
#这个“新的”request.data方法,可以解码所有的数据格式,都是DRF的功劳!!
return HttpResponse("POST")
a.当使用postman发送POST请求,使用json发送数据,发送的数据格式必须是json格式
前端在post方法中,打印request.data,得到结果
{'name': 'alex', 'age': 45}
b.当使用postman发送POST请求,使用url-encoded发送数据
前端在post方法中,打印request.data,得到结果
<QueryDict: {'alex': [''], 'dudu': ['']}>