OK - [GET]:服务器成功返回用户请求的数据,该操做是幂等的(Idempotent)。 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。 Accepted - [*]:表示一个请求已经进入后台排队(异步任务) NO CONTENT - [DELETE]:用户删除数据成功。 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操做,该操做是幂等的。 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。 Forbidden - [*] 表示用户获得受权(与401错误相对),可是访问是被禁止的。 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操做,该操做是幂等的。 Not Acceptable - [GET]:用户请求的格式不可得(好比用户请求JSON格式,可是只有XML格式)。 Gone -[GET]:用户请求的资源被永久删除,且不会再获得的。 Unprocesable entity - [POST/PUT/PATCH] 当建立一个对象时,发生一个验证错误。 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将没法判断发出的请求是否成功。 更多看这里:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 经常使用状态码列表
1
2
3
|
{
error:
"Invalid API key"
}
|
1
2
3
4
5
6
|
GET
/
collection:返回资源对象的列表(数组)
GET
/
collection
/
resource:返回单个资源对象
POST
/
collection:返回新生成的资源对象
PUT
/
collection
/
resource:返回完整的资源对象
PATCH
/
collection
/
resource:返回完整的资源对象
DELETE
/
collection
/
resource:返回一个空文档
|
1
2
3
4
5
6
|
{
"link"
: {
"rel"
:
"collection https://www.example.com/zoos"
,
"href"
:
"https://api.example.com/zoos"
,
"title"
:
"List of zoos"
,
"type"
:
"application/vnd.yourformat+json"
}}
|
摘自:http://www.ruanyifeng.com/blog/2014/05/restful_api.html html
路由系统:python
urlpatterns = [ url(r'^users', Users.as_view()), ]
CBV视图:web
from django.views import View from django.http import JsonResponse class Users(View): def get(self, request, *args, **kwargs): result = { 'status': True, 'data': 'response data' } return JsonResponse(result, status=200) def post(self, request, *args, **kwargs): result = { 'status': True, 'data': 'response data' } return JsonResponse(result, status=200)
url.pydjango
1
2
3
4
5
6
|
from
django.conf.urls
import
url, include
from
web.views.s1_api
import
TestView
urlpatterns
=
[
url(r
'^test/'
, TestView.as_view()),
]
|
views.pyjson
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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请求,响应内容'
)
|
上述是rest framework框架基本流程,重要的功能是在APIView的dispatch中触发。api
from django.conf.urls import url, include from web.viewsimport TestView urlpatterns = [ url(r'^test/', TestView.as_view()), ] urls.py
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.request import Request from rest_framework import exceptions token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812', ] class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ 用户认证,若是验证成功后返回元组: (用户,用户Token) :param request: :return: None,表示跳过该验证; 若是跳过了全部认证,默认用户和Token和使用配置文件进行设置 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN() else: self.auth = None (user,token)表示验证经过并设置用户名和Token; AuthenticationFailed异常 """ val = request.query_params.get('token') if val not in token_list: raise exceptions.AuthenticationFailed("用户认证失败") return ('登陆用户', '用户token') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ # 验证失败时,返回的响应头WWW-Authenticate对应的值 pass class TestView(APIView): authentication_classes = [TestAuthentication, ] permission_classes = [] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) return Response('GET请求,响应内容') def post(self, request, *args, **kwargs): return Response('POST请求,响应内容') def put(self, request, *args, **kwargs): return Response('PUT请求,响应内容')
#!/usr/bin/env python # -*- coding:utf-8 -*- from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import BaseAuthentication from rest_framework.request import Request from rest_framework import exceptions token_list = [ 'sfsfss123kuf3j123', 'asijnfowerkkf9812', ] class TestAuthentication(BaseAuthentication): def authenticate(self, request): """ 用户认证,若是验证成功后返回元组: (用户,用户Token) :param request: :return: None,表示跳过该验证; 若是跳过了全部认证,默认用户和Token和使用配置文件进行设置 self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN() else: self.auth = None (user,token)表示验证经过并设置用户名和Token; AuthenticationFailed异常 """ import base64 auth = request.META.get('HTTP_AUTHORIZATION', b'') if auth: auth = auth.encode('utf-8') auth = auth.split() if not auth or auth[0].lower() != b'basic': raise exceptions.AuthenticationFailed('验证失败') if len(auth) != 2: raise exceptions.AuthenticationFailed('验证失败') username, part, password = base64.b64decode(auth[1]).decode('utf-8').partition(':') if username == 'alex' and password == '123': return ('登陆用户', '用户token') else: raise exceptions.AuthenticationFailed('用户名或密码错误') def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ return 'Basic realm=api' class TestView(APIView): authentication_classes = [TestAuthentication, ] permission_classes = [] def get(self, request, *args, **kwargs): print(request.user) print(request.auth) return Response('GET请求,响应内容') def post(self, request, *args, **kwargs): return Response('POST请求,响应内容') def put(self, request, *args, **kwargs): return Response('PUT请求,响应内容')
c. 多个认证规则跨域
d. 认证和权限数组
e. 全局使用服务器
上述操做中均是对单独视图进行特殊配置,若是想要对全局进行配置,则须要再配置文件中写入便可。restful
1
2
3
|
{
error:
"Invalid API key"
}
|
1
2
3
4
5
6
|
GET
/
collection:返回资源对象的列表(数组)
GET
/
collection
/
resource:返回单个资源对象
POST
/
collection:返回新生成的资源对象
PUT
/
collection
/
resource:返回完整的资源对象
PATCH
/
collection
/
resource:返回完整的资源对象
DELETE
/
collection
/
resource:返回一个空文档
|