2015-07-12 13 views
1

首先,我是Python的總數n00b。我正在使用github-flask和flask,顯然是從GitHub API中提取數據。我正在嘗試使用contents_url並檢索文件。從GitHub的API的URL是這樣的:如何使用github-flask爲{+ path}提供URL參數?

// json 
{ 
    ... 
    "contents_url": "https://api.github.com/repos/<org_name>/<repo_name>/contents/{+path}" 
    ... 
} 

...當我試圖把那個給GitHub的瓶比如我得到一個類型錯誤,「類型錯誤:請求()得到了一個意想不到的關鍵字參數「路徑'「使用:

# python 
contents = github.get(repo['contents_url'], path='.gitignore') 

我很確定我缺少一些簡單的東西。我不必訴諸字符串操縱嗎?

回答

4

Python推薦的字符串插值法是.format方法。您的代碼將與工作,只是一些小的改動:

contents = github.get(repo['contents_url'].format(path='.gitignore')) 

但你也必須改變你的contents_url略:

https://api.github.com/repos/<org_name>/<repo_name>/contents/{path} 

只是要小心 - .format插值基於大括號,所以任何文字大括號都需要被轉義。更多信息,請訪問:https://docs.python.org/3/library/string.html#formatstrings


編輯:正如你在下面的評論中提到,該URL直接從GitHub的API來了,你不能/不應該改變它。事實證明,他們正在使用RFC 6570網址模板(請參閱https://developer.github.com/v3/#hypermedia)。如果您使用我在下面建議的uritemplate庫,代碼將如下所示:

from uritemplate import expand 

# ... 

contents = github.get(expand(repo['contents_url'], {'path': '.gitignore'})) 
+0

謝謝。我不能 - 也不應該 - 更改'contents_url',因爲它是由GitHub API提供的一個字符串。我希望能夠簡單地使用它。 – kalisjoshua

+0

它檢查GitHub API是否使用[RFC 6570](http://tools.ietf.org/html/rfc6570)URL模板(請參閱https://developer.github.com/v3/#hypermedia)。你會想要使用一個合適的庫。它看起來像[uritemplate](https://github.com/uri-templates/uritemplate-py)可能是最好的開始。 – artlogic

+0

我還沒有機會嘗試這個,但它聽起來不錯。我會盡力去解決它。 – kalisjoshua

相關問題