django中設(shè)置返回的狀態(tài)碼和頭部信息
下面先給出我工作中使用到的代碼:
response = ReturnJson(data, status=401).get()
return response
其中,ReturnJson是自己定義的類,用戶返回json格式,做接口使用的.
from django.http import JsonResponse
class ReturnJson(object):
def __init__(self, data, status=None):
# status = status是設(shè)置返回的狀態(tài)碼
self.response = JsonResponse(data, safe=False, status=status)
# 設(shè)置返回的頭部信息,下面是解決跨域API的問題
self.response['Access-Control-Allow-Origin'] = 'http://local.adx.com'
self.response['Access-Control-Allow-Credentials'] = 'true'
self.response['Access-Control-Allow-Headers'] = 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Allow-Credentials'
def get(self):
return self.response
上面的JsonResponse是繼承于HttpResponseBase(多層繼承)
class HttpResponseBase(six.Iterator):
status_code = 200 # 默認(rèn) 200
# 初始化實例函數(shù)中,有status,下面的對象都是放在 **kwgs中了.
def __init__(self, content_type=None, status=None, reason=None, charset=None):
self._headers = {}
self._closable_objects = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
self.cookies = SimpleCookie()
self.closed = False
if status is not None:
self.status_code = status
self._reason_phrase = reason
self._charset = charset
if content_type is None:
content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
self.charset)
self['Content-Type'] = content_type
剔除CSRF_token對單個的post表單的限制
背景知識
# django的中間件
'django.middleware.csrf.CsrfViewMiddleware',
設(shè)置好了,一般出錯如圖:
# 導(dǎo)入裝飾器
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
@login_required(login_url="/api/user/login/")
def add(request):
name = request.POST.get('name') # 加入判斷是否為空
password = request.POST.get('password')
上面贈送了一個裝飾器 @login_required()
下期預(yù)告
django驗證碼