2017-04-20 38 views
1

我一直想寫信給使用Python urllib2與要點如下:發佈與Github的API要旨

def _log_error(information, date=datetime.date.today(), current_time=time.strftime("%H:%M:%S")): 
    log_string = """ 
    Info: {} 
    Date: {} 
    Time: {} 
    """.format(information, date, current_time) 
    filename = "<file>" 
    token = "<token>" 
    access_url = "https://api.github.com/gists/{}".format(filename) 
    req = urllib2.Request(access_url) 
    req.add_header("Authorization", "token {}".format(token)) 
    req.add_header("Content-Type", "application/json") 
    json_data = {"content": log_string} 
    urllib2.urlopen(req, data=json.dumps(json_data)) 

然而,每次我嘗試這樣做,我得到以下錯誤:

Traceback (most recent call last): 
    File "printer.py", line 324, in <module> 
    _log_error("test") 
    File "printer.py", line 69, in _log_error 
    urllib2.urlopen(req, data=json.dumps(json_data)) 
    File "C:\Python27\lib\urllib2.py", line 154, in urlopen 
    return opener.open(url, data, timeout) 
    File "C:\Python27\lib\urllib2.py", line 435, in open 
    response = meth(req, response) 
    File "C:\Python27\lib\urllib2.py", line 548, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "C:\Python27\lib\urllib2.py", line 473, in error 
    return self._call_chain(*args) 
    File "C:\Python27\lib\urllib2.py", line 407, in _call_chain 
    result = func(*args) 
    File "C:\Python27\lib\urllib2.py", line 556, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 422: Unprocessable Entity 

是什麼原因造成這個錯誤,我怎麼能解決這個問題,而無需使用外部庫(如requests)?

回答

1

要創建一個gist,使用Create Gist端點需要以下JSON格式:

{ 
    "description": "the description for this gist", 
    "public": true, 
    "files": { 
    "file1.txt": { 
     "content": "String file contents" 
    } 
    } 
} 

下面將地圖descriptionpublicfilename正確的領域和你的3個內容領域infodatecurrent_time

import urllib2 
import json 
import datetime 
import time 

token = "YOUR_TOKEN" 
access_url = "https://api.github.com/gists" 

filename = "file.txt" 
description = "the description for this gist" 
public = "true" 

information = "some info" 
date = datetime.date.today() 
current_time = time.strftime("%H:%M:%S") 

data = """{ 
    "description": "%s", 
    "public": %s, 
    "files": { 
    "%s": { 
     "content": "info : %s,date: %s, current_time: %s" 
    } 
    } 
}""" 

json_data = data % (description, public, filename, information, date, current_time) 

req = urllib2.Request(access_url) 
req.add_header("Authorization", "token {}".format(token)) 
req.add_header("Content-Type", "application/json") 
urllib2.urlopen(req, data=json_data) 
+0

這會在每次運行時創建一個要點...我不想繼續創建一個,我想編輯sa我一遍又一遍地看着 – age97701

+0

https://developer.github.com/v3/gists/#edit-a-gist。它需要參數中的要點'id'而不是'filename' –