What is the cleanest way to do HTTP POST with basi

2019-02-05 16:52发布

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

Using only the Python core libs.

3条回答
放我归山
2楼-- · 2019-02-05 17:06

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

查看更多
聊天终结者
3楼-- · 2019-02-05 17:26

Hackish workaround works:

`urllib.urlopen("https://username:password@hostname/path", data)` 

Lot of people don't realize that old syntax for specifying username and password in URL works in urllib.urlopen. It doesn't appear the username or password require any encoding, except perhaps if the password included an @ symbol.

查看更多
不美不萌又怎样
4楼-- · 2019-02-05 17:30

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.

查看更多
登录 后发表回答