python中实现接口调用的方法有哪些-创新互联
本篇文章给大家分享的是有关python中实现接口调用的方法有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

python中调用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 content3. 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以上就是python中实现接口调用的方法有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联成都网站设计公司行业资讯频道。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
本文标题:python中实现接口调用的方法有哪些-创新互联
浏览路径:http://www.jxjierui.cn/article/cccddc.html


咨询
建站咨询
