REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”或“表现层状态转化”。
urls
urlpatterns = [
url(r'^users', Users.as_view()),
]
view(视图)
from django.views import View
from django.http import JsonResponse
class Users(View):
def get(self, request, *args, **kwargs):
result = {
'code': 0,
'data': 'response data'
}
return JsonResponse(result, status=200)
def post(self, request, *args, **kwargs):
result = {
'code': 0,
'data': 'response data'
}
return JsonResponse(result, status=200)
基于Django REST Framework框架实现
**在settings中注册 'rest_framework',**```
from django.conf.urls import url, include
from web.views.s1_api import TestView
urlpatterns = [
url(r'^test/', TestView.as_view()),
]
```
视图
from rest_framework.views import APIView
from rest_framework.response import Response
class TestView(APIView):
def dispatch(self, request, *args, **kwargs):
"""
请求到来之后,都要执行dispatch方法,dispatch方法根据请求方式不同触发 get/post/put等方法
注意:APIView中的dispatch方法有好多好多的功能
"""
return super().dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
return Response('GET请求,响应内容')
def post(self, request, *args, **kwargs):
return Response('POST请求,响应内容')
def put(self, request, *args, **kwargs):
return Response('PUT请求,响应内容')
上述就是使用Django REST framework框架搭建API的基本流程,重要的功能是在APIView的dispatch中触发。
在django自定义 RESTful
在页面中写<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>home</title>
</head>
<body>
<form action="http://127.0.0.1:8989/index/" method="post">
<input type="text" name=username>
<input type="submit">
</form>
<button id="b1">点我发跨域请求</button>
<div id="box1"></div>
<script src="jquery-3.3.1.min.js"></script>
<script>
function func(data) {
console.log(data);
console.log(data.name);//ok
}
</script>
<script src="http://127.0.0.1:8989/index/"></script>
<script>
$('#b1').click(function () {
$.ajax({
url:'http://127.0.0.1:8989/index/',
type:'get',
success:function (response_ret) {
console.log(response_ret);
console.log(response_ret.name);
}
})
})
</script>
</body>
</html>
在视图中
```
data = {'name': 'bigc', 'age': 18}
def index(request):
# 获取form post请求的数据
if request.method == 'POST':
print(request.POST.get('username'))
return HttpResponse('func({})'.format(json.dumps(data)))
```
在中间件中写入如下
from django.utils.deprecation import MiddlewareMixin
class Cors(MiddlewareMixin):
def process_response(self, request, response):
# 指定的ip可以发送跨域请求
# response['Access-Control-Allow-Origin'] = 'http://localhost:63342'
# 所有的跨域访问都响应
response['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
# 给contentType 为application/json的放行
response['Access-Control-Allow-Headers'] = 'Content-Type'
# 给PUT,DELETE,放行
response['Access-Control-Allow-Methods'] = 'PUT, DELETE'
return response