Django的拾遺

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í)例函數(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對單個(gè)的post表單的限制

背景知識

# django的中間件
'django.middleware.csrf.CsrfViewMiddleware',  

設(shè)置好了,一般出錯(cuò)如圖:

csrf_token報(bào)錯(cuò)
# 導(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')

上面贈(zèng)送了一個(gè)裝飾器 @login_required()

下期預(yù)告

  django驗(yàn)證碼
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容