0

I need to rewrite the following function using only the python standard library.

def request_release_info(self):
    req = requests.get('https://api.github.com/repos/user/repo/releases/latest',
                       auth=('user', 'token'))
    content = req.json()
    return content

So I need to replace Requests by Urllib/Urllib2 but I'm unable to find a way to pass my username and my token in a similar way.

Thank you for your help !

mandok
  • 492
  • 1
  • 5
  • 20

2 Answers2

0
import urllib, json

result = urllib.urlopen('https://<My_Token>:x-oauth-basic@api.github.com/repos/<user>/<repo>/releases/latest')
r = json.load(result.fp)

print r
result.close()
mandok
  • 492
  • 1
  • 5
  • 20
0

This is example usage of your code, but don't forget about error processing.

from urllib import request
from urllib import error
from base64 import b64encode

def request_release_info(self):
    # build authorization
    user_and_pass = b64encode(b"username:password").decode("ascii")

    # first, we build request
    my_req = request.Request('https://api.github.com/repos/user/repo/releases/latest')

    # then attach auth header
    my_req.add_header('Authorization', 'Basic %s' % user_and_pass)

    # and after that try to execute it
    try:
        content = request.urlopen(my_req)
    except error.HTTPError:
        content = "add error processing, example for wrong log/password"

    return content
mrDinkelman
  • 488
  • 1
  • 9
  • 18