繁体   English   中英

在 Python 中使用基本身份验证进行 HTTP POST 的最干净方法是什么?

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

在 Python 中使用基本身份验证进行 HTTP POST 的最干净方法是什么?

仅使用 Python 核心库。

说真的,只需使用requests

import requests
resp = requests.post(url, data={}, auth=('user', 'pass'))

它是一个纯 python 库,安装就像easy_install requestspip install requests一样简单。 它有一个非常简单易用的 API,它修复了urllib2中的错误,因此您不必这样做。 不要因为愚蠢的自我强加要求而让你的生活变得更艰难。

黑客的解决方法有效:

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

很多人没有意识到在 URL 中指定用户名和密码的旧语法在urllib.urlopen中有效。 用户名或密码似乎不需要任何编码,除非密码包含“@”符号。

如果您定义了 url、用户名、密码和一些后期数据,这应该可以在 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

使用 urllib2 进行基本身份验证的完整教程:* http://www.voidspace.org.uk/python/articles/authentication.shtml

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM