Python请求:auth +自定义标头

时间:2017-02-07 01:16:06

标签: python curl

我正在尝试使用以下curl命令在Python 2.7中工作:

curl --header "Accept: application/vnd.github.korra-preview" --user [username]:[password] https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1

(基本上只是从GitHub组织获取协作者列表) 这是利用GitHub API v3 - https://developer.github.com/v3/orgs/outside_collaborators/

我已阅读了Requests库文档,但无法弄清楚如何传递BOTH授权和自定义标头。有谁知道怎么做?

这是我到目前为止编写的代码。如何在get请求中包含auth和varHeaders?

import requests

varUsername = raw_input("GitHub username:\n")
varPassword = raw_input("GitHub password:\n")

varHeaders = {'Accept':'application/vnd.github.korra-preview'}

#req = requests.get('https://api.github.com/user/repos',auth=(varUsername,varPassword))
req = requests.get('https://api.github.com/orgs/myorg/outside_collaborators?per_page=100\&page=1',auth=(varUsername,varPassword))
print req.status_code
print req.headers
print req.encoding
print req.text
print req.json()

1 个答案:

答案 0 :(得分:0)

您可以添加第三个参数,格式为'headers = varHeaders'

req = requests.get('https://api.github.com/orgs/myorg/outside_coll‌​aborators?per_page=1‌​00\&page=1',auth=(va‌​rUsername,varPasswor‌​d),headers=varHeader‌​s)

感谢Brendan指出这一点!