2015-12-18 62 views
0

我只需要使用python標準庫重寫下面的函數。如何從請求到Urllib2

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 

所以我需要以取代的urllib/urllib2的請求,但我無法找到一個方法來傳遞我的用戶名和我類似的方式標記。

謝謝你的幫助!

+0

你是在Python 2還是3? – senshin

+0

我在python 2.7.11 – mandok

+0

你試過這個嗎? http://stackoverflow.com/q/2407126/ – senshin

回答

0
import urllib, json 

result = urllib.urlopen('https://<My_Token>:[email protected]/repos/<user>/<repo>/releases/latest') 
r = json.load(result.fp) 

print r 
result.close() 
0

這是你的代碼的使用例子,但不要忘了錯誤處理。

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