python調(diào)用接口的4種方式代碼實例
這篇文章主要介紹了python調(diào)用接口的4種方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python結(jié)合多線程爬取英雄聯(lián)盟皮膚(原理分析)
多線程是為了同步完成多項任務(wù),不是為了提高運行效率,而是為了提高資源使用效率來提高系統(tǒng)的效率。這篇文章主要介紹了python爬取英雄聯(lián)盟皮膚結(jié)合多線程的方法,需要的朋友可以參考下2021-05-05Python基本類型的連接組合和互相轉(zhuǎn)換方式(13種)
這篇文章主要介紹了Python中基本類型的連接組合和互相轉(zhuǎn)換13種方式,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12python實現(xiàn)n個數(shù)中選出m個數(shù)的方法
今天小編就為大家分享一篇python實現(xiàn)n個數(shù)中選出m個數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11