使用Python请求为GitHub Enterprise创建令牌

时间:2014-09-24 00:36:22

标签: python python-2.7 github python-requests github-api

我正在尝试为我的脚本创建一个令牌,以便它可以访问我的GitHub Enterprise帐户上的私人仓库。我目前正在尝试这个:

username = 'my_username'
password = getpass.getpass('GitHub Password: ')

payload = {
    'note': 'info about token'
}
url = 'https://github.my_company_name.com/api/v3/authorizations'
r = requests.post(url, auth=(username, password), data=payload)

但是我收到了这个错误:

requests.exceptions.ConnectionError: ('Connected aborted.', error(10061, 'No connection could be made because the target machine actively refused it'))

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

import requests
from bs4 import BeautifulSoup
URL="https://github.com/session"

# Define User Agent
headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"}

username="username"
password="password"

# Create session to crawl authenticated sessions
s=requests.Session()

#Update User Agent in the session created
s.headers.update(headers)

#Get URL using the session created
r=s.get(URL)

#Parse the webspage to find the 'authenticity_token'

soup=BeautifulSoup(r.content)
authenticity_token= soup.find("input",{"name":"authenticity_token"})['value']

# Create Login Data
login_data={"authenticity_token":authenticity_token,
"login":username,
"password":password,
"commit":"Sign in"}

#Now login
r=s.post(URL, data=login_data)

#Test it
soup=BeautifulSoup(r.content)
print soup.find(class_="css-truncate-target").text #This should print your username

登录后即可完成所有操作: - )

希望有所帮助。