Django JsonResponse does not automatically set cookie s

Posted by ankur0101 on Tue, 22 Oct 2019 17:21:54 +0200

[background]

At present, we are doing a web project with front-end and back-end separation. The back-end uses django framework, and all API s only return json. In this process, we encounter a problem that all json response django will not actively set the cookies of response object, which further makes the cookie value of csrftoken never appear in response. .

 

[2. Solution 1]

The solution of this scheme is: since django does not actively set the value of csrftoken, it simply sets it by itself.

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie
class GetIDCView(View):
    """
    //Realize IDC information query
    """
    def get(self,request,pk):
        logger.debug(f"Query all idc ")
        qs = IDC.objects.all().values('name','city','id')
        # hold QuerySet Turn list
        _lqs = [i for i in qs]
        rst = {
            'message': '',
            'code': 0,
        }
        rst['data'] = {
            'idcs': _lqs
        }
        response = JsonResponse(rst)
        # Hand work done set_cookie
        response.set_cookie('csrftoken','csrf-token-value')
        return response

 

Write a client program to check cookie s

import requests

if __name__ == "__main__":
    session = requests.Session()
    response = session.get("http://127.0.0.1:8080/hosts/idcs/")
    print(response.cookies)

 

View the returned cookie value

python3 getcookie.py 
< RequestsCookieJar[ < Cookie csrftoken=csrf-token-value for 127.0.0.1/ > ] >

 

The problem of this scheme is that setting cookie s is a part of business logic and is not easy to maintain.

 

[3. Solution 2]

The solution of this scheme is to directly use the decorator provided by django. This scheme is simply mentioned in the official document of django (only four lines of words), so the difficulty lies in whether you have carefully read the official document.

from django.views import View
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie

class GetIDCView(View):
    """
    //Realize IDC information query
    """
    @method_decorator(ensure_csrf_cookie)
    def get(self,request,pk):
        # If pk == None Description is to find all IDC Example
        logger.debug(f"Query all idc ")
        qs = IDC.objects.all().values('name','city','id')
        # hold QuerySet Turn list
        _lqs = [i for i in qs]
        rst = {
            'message': '',
            'code': 0,
        }
        rst['data'] = {
            'idcs': _lqs
        }
        return JsonResponse(rst)

 

Viewing effect

python3 getcookie.py 
< RequestsCookieJar[< Cookie csrftoken=iQQhG2NETVTDnWTAVYBXji1ehLdWesKIGCCxTC1icyIapoS6LrpdUYOZc39qJsto for 127.0.0.1/ > ] >

The advantage of this scheme is that View only needs to deal with business logic.

 

Quote from: https://www.sqlpy.com/blogs/books/2/chapters/15/articles/53

Topics: PHP Django Session JSON