pythondjangocsrf-protection

How do I pass a CSRF token using the python-requests library?


I have an app which needs to redirect to another url from outside with some POST data. I have the CSRF token value to the other app. How do I construct a simple POST request with requests library in Python??

csrf_token = "kjsbfckjsdnfcksdnkl"
post_data = {'email': email, 'answer': answer}
response = request.post(URL, data=post_data)

Where do I add the CSRF token?


Solution

  • You can either send the CSRF token as a POST parameter or a HTTP header.

    Edit: a Referer HTTP header is also required by Django's CSRF protection. It needs to have the same origin as the request.

    Using POST parameters:

    post_data = {'email': email, 'answer': answer, 'csrftoken': csrf_token_value}
    headers = {'Referer': URL}
    response = request.post(URL, data=post_data, headers=headers)
    

    Using HTTP headers:

    post_data = {'email': email, 'answer': answer}
    headers = {'X-CSRFToken': csrf_token_value, 'Referer': URL}
    response = request.post(URL, data=post_data, headers=headers)