天天看点

Django的拾遗

django中设置返回的状态码和头部信息

下面先给出我工作中使用到的代码:

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是设置返回的状态码
        self.response = JsonResponse(data, safe=False, status=status)
        # 设置返回的头部信息,下面是解决跨域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 # 默认 200

    # 初始化实例函数中,有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',  
           

设置好了,一般出错如图:

csrf_token报错

# 导入装饰器
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()

下期预告

django验证码