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.
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.
You set cookies in response:
response.set_cookie('cookie', 'MY COOKIE VALUE')
but use if in reqeust cookies
if 'cookie' in request.COOKIES:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With