How to POST Python requests with CSRF token ?

import requests
client = requests.session()

# Retrieve the CSRF token first
URL = ''
client.get(URL) # sets cookie
csrftoken = client.cookies['csrftoken']
print csrftoken #Check if it's getting printed. Sometimes key name could be 'csrf' only

payload = {

r =, data=payload, headers=dict(Referer=URL))

2 Replies to “How to POST Python requests with CSRF token ?”

  1. if i try to fetch the CSRF token i am getting following error
    Traceback (most recent call last):
    File “”, line 12, in
    csrftoken = client.cookies[‘csrftoken’]
    File “C:\Python27\lib\site-packages\requests\”, line 293, in __getitem__
    return self._find_no_duplicates(name)
    File “C:\Python27\lib\site-packages\requests\”, line 351, in _find_no_duplicates
    raise KeyError(‘name=%r, domain=%r, path=%r’ % (name, domain, path))
    KeyError: “name=’csrfmiddlewaretoken’, domain=None, path=None”

Leave a Reply

Your email address will not be published. Required fields are marked *