python中调用API的几种方式:
- urllib2
- 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、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
import requests
from lxml import etree
from random import randint
def get_joke():
url="http://www.qiushibaike.com/text/page/"+ str(randint(1,5))
r = requests.get(url)
tree = etree.HTML(r.text)
contentlist = tree.xpath('//div[@class="content"]/span')
jokes = []
for content in contentlist:
content = content.xpath('string(.)') # string() 函数将所有子文本串联起来,# 必须传递单个节点,而不是节点集。
if '查看全文' in content: # 忽略包含“查看原文”笑话
continue
jokes.append(content)
joke = jokes[randint(1, len(jokes))].strip()
return joke
if __name__ == "__main__":
content = get_joke()
print(content)
二、python一个http接口服务,给别人调用 ----之Flask
案例1、flask、get接口代码实现
# -*- coding: UTF-8 -*-
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/test', methods=["GET"])
def calculate():
a = request.args.get("a", 0)
b = request.args.get("b", 0)
c = int(a) + int(b)
res = {"result": c}
return jsonify(content_type='application/json;charset=utf-8',
reason='success',
charset='utf-8',
status='200',
content=res)
if __name__ == '__main__':
app.run(host='0.0.0.0',
threaded=True,
debug=False,
调用方式:
http://127.0.0.1:8080/test?a=1&b=4
案例2、post接口flask
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/test', methods=["POST"])
def calculate():
params = request.form if request.form else request.json
print(params)
a = params.get("a", 0)
b = params.get("b", 0)
c = a + b
res = {"result": c}
return jsonify(content_type='application/json;charset=utf-8',
reason='success',
charset='utf-8',
status='200',
content=res)
if __name__ == '__main__':
app.run(host='0.0.0.0',
threaded=True,
debug=True,
port=8080)
调用方式
最常用接口形式
POST API接口:
import json
import requests
if __name__ == '__main__':
url = "http://127.0.0.1:9001/rsa/set_uplod"
headers = {'content-type': 'application/json'}
requestData = {"certificate_no": "56565656565656", "auth_code": "123456"}
ret = requests.post(url, json=requestData, headers=headers)
if ret.status_code == 200:
text = json.loads(ret.text)
print(text)
get API 接口:
import json
import requests
if __name__ == '__main__':
url = "http://127.0.0.1:9001/getSha1Test?message=APP000051527151133935949D49FDC0A86605313931B9BB9A4C87"
ret = requests.get(url)
if ret.status\_code == 200:
text = json.loads(ret.text)
print(text)
三、二、python一个http接口服务,给别人调用 ----之FastAPI
这次选择fastapi,FastAPI是一个现代的、快速(高性能)的web框架,用于基于标准Python类型提示使用Python 3.6+构建api。具有快速、快速编码、更少的错误、直观、简单、简便、健壮。简易而且本地win10能够跑起来。
二、FastAPI的get接口代码实现
1. 安装: pip install fastapi
pip install uvicorn
# !/usr/bin/python
from fastapi import FastAPI
app = FastAPI()
@app.get('/test/a={a}/b={b}')
def calculate(a: int=None, b: int=None):
c = a + b
res = {"res":c}
return res
if __name__ == '__main__':
import uvicorn
uvicorn.run(app=app,
host="0.0.0.0",
port=8080,
workers=1)
接口访问:http://127.0.0.1:8080/test/a=1/b=4
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class Item(BaseModel):
a: int = None
b: int = None
@app.post('/test')
def calculate(request_data: Item):
a = request_data.a
b = request_data.b
c = a + b
res = {"res":c}
return res
if __name__ == '__main__':
import uvicorn
uvicorn.run(app=app,
host="0.0.0.0",
port=8080,
workers=1)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章