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

Question:

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?

Asked By: DeadDjangoDjoker

||

Answers:

In case you are using a recent Django with CsrfMiddleware add it to the post_data dict:

post_data = {'email': email, 'answer': answer, 'csrfmiddlewaretoken': 'yourtoken'}

Check a form if the variable name is correct.

If you want to redirect on the same server, just call die other view function.

Answered By: Klaus D.

Take a look at the official documentation, which covers sending a POST request with a CSRF token.

CSRF tokens are stored in cookies (as far as I know). Since that’s the case, you can store the cookie value as some variable, then use that value in your request.

Answered By: Mr_Spock

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)
Answered By: aumo
Answered By: navyad

I suggest you to use session objects of request library.

Moreover, if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase and A Session object has all the methods of the main Requests API.

Answered By: Ravish Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.