url = 'https://github.abc.defcom/api/v3/repos/abc/def/releases/401/assets?name=foo.sh'
r = requests.post(url, headers={'Content-Type':'application/binary'}, data=open('sometext.txt','r'), auth=('user','password'))
这给了我
>>> r.text
u'{"message":"Not Found","documentation_url":"https://developer.github.com/enterprise/2.4/v3"}'
我哪里错了?
因此,我将提出这样的建议:如果您使用库,它就像以下一样简单:
from github3 import GitHubEnterprise
gh = GitHubEnterprise(token=my_token)
repository = gh.repository('abc', 'def')
release = repository.release(id=401)
asset = release.upload_asset(content_type='application/binary', name='foo.sh', asset=open('sometext.txt', 'rb'))
考虑到这一点,我还要在前面加上“application / binary”并不是真正的媒体类型(参见:https://www.iana.org/assignments/media-types/media-types.xhtml)
接下来,如果您使用read the documentation,您会注意到GitHub需要具有真实SNI(服务器名称指示)的客户端,因此根据您的Python版本,您可能还必须从PyPI安装pyOpenSSL
,pyasn1
和ndg-httpsclient
。
我不确定企业实例的URL是什么,但对于公共GitHub,它看起来像:
https://uploads.github.com/repos/octocat/Hello-World/releases/1/assets?name=foo.sh
因此,您将拥有url
,而且您将需要您的身份验证凭据(在您的情况下,您似乎想要使用基本身份验证)。然后,您将需要在标题中使用有效的媒体类型,例如,
headers = {'Content-Type': 'text/plain'}
你的电话看起来非常正确:
requests.post(url, headers=headers, data=open('file.txt', 'rb'), auth=(username, password))
要获得正确的网址,您应该:
release = requests.get(release_url, auth=(username, password))
upload_url = release.json().get('upload_url')
请注意,这是URITemplate。您需要删除模板或使用像uritemplate.py
这样的库来解析它并使用它来为您构建URL。
最后一个提醒,github3.py(原始示例中的库)为您处理所有这些。
APIv3上传示例没有任何外部依赖项
用法:
GITHUB_TOKEN=<token> ./create-release username/reponame <tag-name> <path-to-upload>
脚本:
#!/usr/bin/env python3
import json
import os
import sys
from urllib.parse import urlencode
from urllib.request import Request, urlopen
repo = sys.argv[1]
tag = sys.argv[2]
upload_file = sys.argv[3]
token = os.environ['GITHUB_TOKEN']
url_template = 'https://{}.github.com/repos/' + repo + '/releases'
# Create.
_json = json.loads(urlopen(Request(
url_template.format('api'),
json.dumps({
'tag_name': tag,
'name': tag,
'prerelease': True,
}).encode(),
headers={
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'token ' + token,
},
)).read().decode())
release_id = _json['id']
# Upload.
with open(upload_file, 'br') as myfile:
content = myfile.read()
_json = json.loads(urlopen(Request(
url_template.format('uploads') + '/' + str(release_id) + '/assets?' \
+ urlencode({'name': os.path.split(upload_file)[1]}),
content,
headers={
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'token ' + token,
'Content-Type': 'application/zip',
},
)).read().decode())
任何语言的超级问题:How to release a build artifact asset on GitHub with a script?