-
-
Save naushad-rahman/d29b09026a727e3bc36abe39955c501b to your computer and use it in GitHub Desktop.
An example of using Python requests to log in and post data to your Django API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
LOGIN_URL = "http://mydjangosite.com/accounts/login/" | |
ENDPOINT_URL = 'http://mydjangosite.com/myendpoint/' | |
''' | |
Create a session. | |
A session will automatically store the cookies that Django | |
sends back to you, like the csrf token and a the session id. You | |
could do it without the session, but then you'd have to save off the | |
cookies manually and remember to pass them along with subsequent | |
requests. | |
''' | |
client = requests.session() | |
client.get(LOGIN_URL) | |
# Django would like the csrf token passed with the data, so we do need to save it off seperately. | |
csrftoken = client.cookies['csrftoken'] | |
''' | |
Log in. | |
''' | |
login_data = {login:"somepersonsname", password:"supergreatpassword", csrfmiddlewaretoken:csrftoken} | |
r1 = client.post(LOGIN_URL, data=login_data) | |
# For some reason, we are issued a new csrf token after logging in, so update your local copy. | |
csrftoken = client.cookies['csrftoken'] | |
''' | |
Post some data to your login-only API endpoint. | |
''' | |
payload = {'somedata':'asdf', 'someotherdata':'1235', 'csrfmiddlewaretoken':csrftoken} | |
# We use client.post (not requests.post) so that we pass on the cookies that our session stored. | |
r2 = client.post(ENDPOINT_URL, data=payload) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't really comment on ppl's pages and gists, but I will this time!
I have wasted 5 hours digging and testing my code but couldn't get my project to work :(
This tiny sentence: "For some reason, we are issued a new csrf token after logging in, so update your local copy."
has solved my problem! 5 hours!
Thank you, thank you, thank you!