How to POST Python requests with CSRF token ?


import requests
client = requests.session()

# Retrieve the CSRF token first
URL = 'http://www.example.com/'
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 = {
'csrfmiddlewaretoken':csrftoken,
'key1':'value1',
'key2':'value2',
'key3':'value3'
}

r = client.post(URL, 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 “csrf.py”, line 12, in
    csrftoken = client.cookies[‘csrftoken’]
    File “C:\Python27\lib\site-packages\requests\cookies.py”, line 293, in __getitem__
    return self._find_no_duplicates(name)
    File “C:\Python27\lib\site-packages\requests\cookies.py”, 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 *