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:返回一個空文檔
|