[Answer]-Django POST request to my view from Pyres worker – CSRF token

1👍

I think I see the problem.

The way Django’s CSRF protection works is by generating a nonce, then setting a cookie to the value of the nonce, and ensuring the csrfmiddlewaretoken POST value matches the value of the cookie. The rationale is that it makes it a stateless system, which works without any persistent session data.

The problem is that the request you make in the Pyres worker job…

result = urllib2.urlopen('http://127.0.0.1:8000/tasks/nlp/process/', 
                         urllib.urlencode(post_data))

…is coming from the server, not the client, so it won’t have the cookie set.

Assuming the /tasks/nlp/process/ URL is protected such that it can only be accessed by the server, then it’s probably simplest to make the process() view exempt from CSRF checking with…

@csrf_exempt
def process(request):
   ...

…otherwise you’ll have to manually grab the cookie value in the handler() view, and pass it on to the Pyres worker job.

Update

To ensure the process() method can only be called by the server, one simple way would be to check the request object with something like…

@csrf_exempt
def process(request):
    if request.META['REMOTE_ADDR'] != '127.0.0.1':
        # Return some error response here.
        # 403 is traditional for access denied, but I prefer sending 404
        # so 'hackers' can't infer the existence of any 'hidden' URLs
        # from the response code
        raise Http404
    # Now do the thing
    ....

…although there may be some built-in decorator or somesuch to do this for you.

👤Aya

Leave a comment