python調(diào)用接口的4種方式代碼實例
更新時間:2019年11月19日 16:59:13 作者:-零
這篇文章主要介紹了python調(diào)用接口的4種方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了python調(diào)用接口的4種方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
python中調(diào)用API的幾種方式:
- - urllib2
- - httplib2
- - pycurl
- - requests
1.urllib2
import urllib2, urllib
github_url =
'https://api.github.com/user/repos'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None,
github_url, 'user', '***')
auth = urllib2.HTTPBasicAuthHandler(
password_manager)# create an authentication handler
opener = urllib2.build_opener(auth)# create an opener with the authentication handler
urllib2.install_opener(opener)# install the opener
...
request = urllib2.Request(github_url,
urllib.urlencode({
'name': 'Test repo',
'description': 'Some test repository'
}))# Manual encoding required
handler = urllib2.urlopen(request)
print handler.read()
2. httplib2
import urllib, httplib2
github_url = '
h = httplib2.Http(".cache")
h.add_credentials("user", "******", "
data = urllib.urlencode({
"name": "test"
}) resp, content = h.request(
github_url, "POST", data) print content
3. pycurl
import pycurl, json
github_url = "
user_pwd = "user:*****"
data = json.dumps({
"name": "test_repo",
"description": "Some test repo"
})
c = pycurl.Curl()
c.setopt(pycurl.URL, github_url)
c.setopt(pycurl.USERPWD, user_pwd)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()
4. requests
import requests, json
github_url = "
data = json.dumps({'name':'test', 'description':'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))
print r.json
以上幾種方式都可以調(diào)用API來執(zhí)行動作,但requests這種方式代碼最簡潔,最清晰,建議采用。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python基于SMTP協(xié)議實現(xiàn)發(fā)送郵件功能詳解
這篇文章主要介紹了Python基于SMTP協(xié)議實現(xiàn)發(fā)送郵件功能,結(jié)合實例形式分析了Python使用SMTP協(xié)議實現(xiàn)郵件發(fā)送的相關(guān)操作技巧,并總結(jié)分析了Python發(fā)送純文本郵件、郵件附件、圖片郵件等相關(guān)操作技巧,需要的朋友可以參考下2018-08-08
PyTorch?可視化工具TensorBoard和Visdom
這篇文章主要介紹了PyTorch?可視化工具TensorBoard和Visdom,TensorBoard?一般都是作為?TensorFlow?的可視化工具,與?TensorFlow?深度集成,它能夠展現(xiàn)?TensorFlow?的網(wǎng)絡計算圖,繪制圖像生成的定量指標圖以及附加數(shù)據(jù)等,下面來看文章得具體內(nèi)容介紹吧2022-01-01
Python re.split方法分割字符串的實現(xiàn)示例
本文主要介紹了Python re.split方法分割字符串的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-08-08

