Can someone give a python requests example of uploading a release asset in github?

前端 未结 2 433
旧巷少年郎
旧巷少年郎 2021-01-13 05:55
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\'}, da         


        
2条回答
  •  春和景丽
    2021-01-13 06:33

    APIv3 upload example without any external dependencies

    Usage:

    GITHUB_TOKEN= ./create-release username/reponame  
    

    Script:

    #!/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())
    

    Superset question with any language: How to release a build artifact asset on GitHub with a script?

提交回复
热议问题