Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a cookie in Django Rest Framework API

I am trying to set a cookie on my website when a GET request is made to an API end-point.

In my urls.py, I have this:

url(r'^api/cookies/$', views.cookies, name='cookies'),

which points to this view:

@api_view(['GET'])
def cookies(request):
    if request.method == 'GET':
        response = HttpResponse('Setting a cookie')
        response.set_cookie('cookie', 'MY COOKIE VALUE')
        if 'cookie' in request.COOKIES:
            value = request.COOKIES['cookie']
            return Response('WORKS')
        else:
            return Response('DOES NOT WORK')

In other words, when this view is loaded through a GET method, I am setting a cookie. If the cookie is set properly, I return 'WORKS', otherwise, I return 'DOES NOT WORK'.

Now, I am sending a GET request to this URL, and I get 'DOES NOT WORK', which means the cookie is not set properly. What am I doing wrong? How can I fix this? Note: I am using Django Rest Framework for my views.

like image 936
darkhorse Avatar asked Sep 23 '16 19:09

darkhorse


2 Answers

It happens because the response in which you are setting the cookie is never sent to the browser, thus no cookie is set. Note the changes below

@api_view(['GET'])
def cookies(request):
    if request.method == 'GET':
        if 'cookie' in request.COOKIES:
            value = request.COOKIES['cookie']
            response = HttpResponse('Works')
            return response
        else:
            response = HttpResponse('Does Not Works')
            response.set_cookie('cookie', 'MY COOKIE VALUE')
            return response

when you run it first time it will show 'Does Not Work' since the cookie is not set yet so if condition will fail, but in second time it would work.

like image 50
Ankush Verma Avatar answered Sep 22 '22 16:09

Ankush Verma


You set cookies in response:

response.set_cookie('cookie', 'MY COOKIE VALUE')

but use if in reqeust cookies

if 'cookie' in request.COOKIES:
like image 36
Windsooon Avatar answered Sep 24 '22 16:09

Windsooon