What is the cleanest way to do HTTP POST with Basic Auth in Python?
Using only the Python core libs.
To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server. Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.
Note: The HTTP basic authentication scheme can be considered secure only when the connection between the web client and the server is secure. If the connection is insecure, the scheme does not provide sufficient security to prevent unauthorized users from discovering the authentication information for a server.
We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.
Seriously, just use requests
:
import requests resp = requests.post(url, data={}, auth=('user', 'pass'))
It's a pure python library, installing is as easy as easy_install requests
or pip install requests
. It has an extremely simple and easy to use API, and it fixes bugs in urllib2
so you don't have to. Don't make your life harder because of silly self-imposed requirements.
Hackish workaround works:
urllib.urlopen("https://username:password@hostname/path", data)
A lot of people don't realize that the old syntax for specifying username and password in the URL works in urllib.urlopen
. It doesn't appear the username or password require any encoding, except perhaps if the password includes an "@" symbol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With