[英]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 requests
或pip 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.