Github-api giving 404 when passing json-data with python + urllib2

后端 未结 4 1032
离开以前
离开以前 2020-12-21 04:31

I have the following code, which should perform the first part of creating a new download at github. It should send the json-data with POST.

jsonstring = \'{         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 04:43

    I have provided an answer as to how to POST JSON data to the V3 API without any authentication, but seen as you have identified that the original problem was with not setting up your OAUTH tokens correctly, I thought I would provide a programatic solution to getting one (this implementation gets a token every time the script is run, whereas in practice it would be done just once, and the token would be stored localy).

    import urllib2
    import json
    import getpass
    import base64
    
    # Generate a token from the username and password.
    # NOTE: this is a naive implementation. Store pre-retrieved tokens if possible.
    username = 'pelson'
    passwd = getpass.getpass() # <- this just puts a string in passwd (plaintext)
    
    req = urllib2.Request("https://api.github.com/authorizations")
    
    # add the username and password info to the request
    base64string = base64.encodestring('%s:%s' % (username, passwd)).replace('\n', '')
    req.add_header("Authorization", "Basic %s" % base64string)
    
    data = json.dumps({"scopes":["repo"], "note":"Access to your repository."})
    result = urllib2.urlopen(req, data)
    result = json.loads('\n'.join(result.readlines()))
    token = result['token']
    

    Once you have this token, it can be used for any "repo" scope actions. Lets add a new issue to a repository:

    # add an issue to the tracker using the new token
    repo = 'name_of_repo'
    data = json.dumps({'title': 'My automated issue.'})
    req = urllib2.Request("https://api.github.com/repos/%s/%s/issues" % (username, repo))
    req.add_header("Authorization", "token %s" % token)
    result = urllib2.urlopen(req, data)
    
    result = json.loads('\n'.join(result.readlines()))
    print result['number']
    

    Hope that helps somebody.

提交回复
热议问题