如何使用 python 请求将 tar.gz 和 jar 文件作为 GitHub 资产上传?

How to upload tar.gz and jar files as GitHub assets using python requests?

在某个目录中,我有一个.tar.gz和一个.jar 工件。我想使用请求上传这些资产以进行发布。不幸的是,我无法让它工作。

假设这个 .tar.gz 文件被称为 peaches。tar.gz 这是我尝试做的:

headers = {'Content-Type': 'application/gzip'}
myAuth = {'MyGithubName', 'myToken'}
requests.post('https://api.github.com/repos/MyGithubName/MyRepo/releases/SomeIDNumber/assets?name=peaches.tar.gz, auth= myAuth, headers= headers, data= open('peaches.tar.gz', 'rb'))

来自 Github documentation,要上传资产,您需要 upload_url :

POST https://<upload_url>/repos/:owner/:repo/releases/:id/assets?name=foo.zip

您需要从 get release API (list releases, get a single release or get latest release). You can find here 中提取此 url :

Note: This returns an upload_url key corresponding to the endpoint for uploading release assets. This key is a hypermedia resource.

上传url是一个URI template例如:

https://uploads.github.com/repos/bertrandmartel/ustream-dl/releases/8727946/assets{?name,label}

要构建它,您可以使用 uritemplate module & expand the name property (also described here)

以下将获取最新版本并将 peaches.tar.gz 资产上传到其中(名称为 peaches.tar.gz):

import requests 
from uritemplate import URITemplate

repo = 'bertrandmartel/ustream-dl'
access_token = 'YOUR_ACCESS_TOKEN'

r = requests.get('https://api.github.com/repos/{0}/releases/latest'.format(repo))

upload_url = r.json()["upload_url"]

t = URITemplate(upload_url)
asset_url = t.expand(name = 'peaches.tar.gz')

headers = {
    'Content-Type': 'application/gzip',
    'Authorization': 'Token {0}'.format(access_token)
}
r = requests.post(
    asset_url, 
    headers = headers, 
    data = open('peaches.tar.gz', 'rb').read()
)
print(r.status_code)
print(r.text)