Login and upload file using Python 'requests'

http, python, python-requests

Solution

Make a session and then use that session to do your requests -

sessionObj = requests.session()
sessionOj.get(...) # Do whatever ...

A session persists your cookies for future requests. And use post parameters for username,password as the parameters are required to login in `login.php` , not auth username password. Also use `files` parameter to upload files. So the final code is -

import requests

sessionObj = requests.session()
url1='http://www.abc.com/login.php'
r = sessionObj.post(url1, params={'username':'usernamehere' , 'password':'password here'})
print r.status_code //msg:'200'


filehandle = open('./tmp.txt')
url2='http://www.abc.com/uploader.php'
r = sessionObj.post(url2, data={},files = {'upload':filehandle})
print r.text

Docs.

Problem

I need to login and upload a file . The problem I am facing is, login page is different from uploading page. If I have to do it manually, I'll login (`login.php`) to the site and then navigate to the upload page (`uploader.php`) to upload the file. This what I have written: ``` import requests url1='http://www.abc.com/login.php' r = requests.post(url1, auth=('uname', 'pword')) print r.status_code //msg:'200' payload = {'upload':open('./tmp.txt')} url2='http://www.abc.com/uploader.php' r = requests.post(url2, data=payload) print r.text //msg: "you must first login to upload the file" ``` My code is obviously not working as expected. Login part is working correctly but not uploading part. Please how can I accomplish my goal. UPDATE: To give more insight into my question, I am giving `login.php` and `uploader.php` file details: login.php ``` <form method="POST" action="login.php" class="login"> <input type="text" name="username"></input> <input type="password" name="password"></input> <input type="submit" value="Login"></input> ``` uploader.php ``` <form action='uploader.php' method='POST' id='form' class='upload' enctype="multipart/form-data" > <input type='file' name='upload' id='file'></input> <input type='button' value='Analyze' name='button' onclick='javascript: checkuploadform(false)'> ```

Original source