python - Python 上的 REST GET 请求发送命名参数

标签 python rest urllib2

我在 Linux 上使用 bash 中的curl 进行游戏,但现在我需要将我的脚本移至 python 以便更有效。 在 python 上执行以下操作的最佳方法是什么?

curl baseuri:port/resource -u user:pswd

我已经玩过 urllib2,但我不知道如何发送“-u user:pswd”

最佳答案

您需要使用 HTTPPasswordMgrWithDefaultRealm instance处理身份验证,并添加 HTTPBasicAuthHandler handler响应身份验证质询:

import urllib2

url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'

pwmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwmgr.add_password(None, url, username, password)    
authhandler = urllib2.HTTPBasicAuthHandler(passman)

opener = urllib2.build_opener(authhandler)
response = opener.open(theurl)

是的,这是少数。

如果您可以安装第 3 方库,请添加使用 requests library ;这会变得容易得多:

import requests

url = 'baseuri:port/resource'
username = 'user'
password = 'pswd'

response = requests.get(url, auth=(username, password))

关于python - Python 上的 REST GET 请求发送命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25123691/

相关文章:

python - 在 Python 中,如何对有时挂起的函数调用强制超时?

python - Reddit API 返回无用的 JSON

python - 从系列创建一个 pd.Dataframe

python - 如何在 Python 中静态(词法)绑定(bind)名称?

java - 将 Oauth 2.0 添加到基于 Jersey 的 RESTful 服务器

java - 为每个 POST 和接收使用两个相同的类 - REST

rest - Cloudant 批量创建(或更新)的最大大小?

python - urllib3 最大重试错误

python - 如何从三重奏 ReceiveStream 一次读取一行?

python - 在 Python 中使用 if 条件加速逐行循环