您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇文章给大家分享的是有关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 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
以上就是python中实现接口调用的方法有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。