Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Login to webpage from script using Requests and Django

I have written a web application in Django. I need to post some data to a form from a python script. The post (r2) works correctly when login is disabled. I have the request working correctly for the login (r1), but it gives me a 404 error now for the form post (r2). The login doesn't appear to be carried over to the second request. The csrftoken and sessionid are hardcoded for testing because it wasn't recognizing them. Relevant code (url base removed):

url_login='../pecasRunLog/accounts/login/'
url_add_run='../pecasRunLog/model/'+region+'/add_run/'

client = requests.session()
client.get(url_login)
csrftoken = client.cookies['csrftoken']
login_data = {'username':user,'password':password, 'csrfmiddlewaretoken':csrftoken, 'next': '/pecasRunLog/'}
r1=client.post(url_login,data=login_data)

payload={'model_region':region_id,'scendir':scendir, 'mapit_scenario': schema, 'run_name':schema+timestamp, 'run_computer_name':os.environ['COMPUTERNAME'], 'run_computer_ip':get_lan_ip(), 'declared_user':declared_user, 'logged_in_user':getpass.getuser(), 'sd_schema':schema, 'sd_database':database, 'sd_host':get_lan_ip(), 'sd_port':pgport,'mapit_schema':schema, 'mapit_database':database, 'mapit_host':get_lan_ip(), 'mapit_port':pgport,'start_date':start_date, 'start_time':start_time, 'end_date':end_date, 'end_time':end_time,'logged_manually':3, 'csrfmiddlewaretoken':csrftoken, 'sessionid':'jtvv50cs3iyo9bjthbr2diujfmrrlsnf'}
r2=requests.post(url_add_run,payload)
like image 911
Jason Hawkins Avatar asked Jul 03 '14 20:07

Jason Hawkins


People also ask

How do I log into a website request?

Your browser sends a HTTP GET request to login page. The website responds with the page, and the page includes a form for you to enter your username and password. You enter your username and password into the form and hit enter. Your browser sends that info (this time using a HTTP POST request) back to the login page.


1 Answers

I just face same problem.

Looks like django use diferent url for login post than the login home page.

This code work for me

import requests
URL1='http://localhost:8000/admin/'
URL='http://localhost:8000/admin/login/?next=/admin/'
UN='bino'
PWD='sendhimin'
client = requests.session()

# Retrieve the CSRF token first
client.get(URL1)  # sets the cookie
csrftoken = client.cookies['csrftoken']

login_data = dict(username=UN, password=PWD, csrfmiddlewaretoken=csrftoken)
r = client.post(URL2, data=login_data, headers={"Referer": "foo"})
like image 190
Bino Oetomo Avatar answered Oct 26 '22 10:10

Bino Oetomo