esamatti
esamatti

Reputation: 18973

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.

Upvotes: 63

Views: 125863

Answers (4)

prempre
prempre

Reputation: 1

from requests.auth import HTTPBasicAuth
from requests_toolbelt import MultipartEncoder
import requests

file = "You file full path"
filename = "your file name with the extension"

with open(file, 'rb') as pdf_file:
    multipart_data = MultipartEncoder(fields={'object': (filename, pdf_file, 'application/pdf')})
    headers = {
            'Content-Type': multipart_data.content_type,
            'Authorization': f'Basic {authorization}',
            'User-Agent':'Your python user agent',
    }
    auth = HTTPBasicAuth(username, password)

    # Send the POST request
    response = requests.post(file_url, data=multipart_data, headers=headers, auth=auth)

print(response.status_code)

Upvotes: -1

user1740078
user1740078

Reputation: 501

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.

Upvotes: 11

Corey Goldberg
Corey Goldberg

Reputation: 60634

if you define a url, username, password, and some post-data, this should work in Python2...

import urllib2

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
auth_handler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
content = urllib2.urlopen(url, post_data)

example from official Python docs showing Basic Auth in urllib2: * http://docs.python.org/release/2.6/howto/urllib2.html

full tutorial on Basic Authentication using urllib2: * http://www.voidspace.org.uk/python/articles/authentication.shtml

Upvotes: 6

Zach Kelling
Zach Kelling

Reputation: 53859

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.

Upvotes: 153

Related Questions