Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cleanest way to do HTTP POST with basic auth in Python?

What is the cleanest way to do HTTP POST with Basic Auth in Python?

Using only the Python core libs.

like image 404
Epeli Avatar asked Jun 06 '11 18:06

Epeli


People also ask

How do you pass basic auth requests in python?

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.

Is Basic Auth safe over HTTPS?

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.

How can I pass the basic HTTP authentication?

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.


2 Answers

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.

like image 131
zeekay Avatar answered Oct 12 '22 13:10

zeekay


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.

like image 24
user1740078 Avatar answered Oct 12 '22 13:10

user1740078