gpt4 book ai didi

python - 如何在 Python 中实现 curl -u?

转载 作者:太空狗 更新时间:2023-10-29 20:13:05 26 4
gpt4 key购买 nike

我正在尝试使用 http://developer.github.com/v3/检索项目问题。这有效:

curl -u "Littlemaple:mypassword" https://api.github.com/repos/MyClient/project/issues

它返回我客户项目的所有私有(private)问题。但是,我无法找到如何在 Python 中实现它。我发现的两种方法(例如 Python urllib2 Basic Auth Problem)都不起作用,它们返回 404 或 403 错误:

def fetch(url, username, password):
"""Wonderful method found on forums which does not work.""""
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))

req = urllib2.Request(url)
f = urllib2.urlopen(req)
return f.read()

...和:

def fetch(url, username, password):
"""Wonderful method found on forums which does not work neither.""""
request = urllib2.Request(url)
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)
return urllib2.urlopen(request).read()

有什么想法吗?提前致谢!

最佳答案

r = requests.get('https://api.github.com', auth=('user', 'pass'))

Python requests 是前往此处的方式。我一直在工作和家中广泛使用 requests 进行各种 Web 服务交互。与之前的产品相比,使用它是一种乐趣。注意:auth 关键字参数适用于任何需要身份验证的调用。因此,您可以谨慎使用它,即您不需要每次调用 GitHub 时都需要它,只有那些需要登录的调用。例如:

r = requests.get('https://api.github.com/gists/starred', auth=('user', 'pass'))

GitHub 登录记录在此处:

http://pypi.python.org/pypi/requests/0.6.1

关于python - 如何在 Python 中实现 curl -u?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6205307/

26 4 0