一、python3写一个http接口服务,给别人调用3
这次选择fastapi,FastAPI是一个现代的、快速(高性能)的web框架,用于基于标准Python类型提示使用Python 3.6+构建api。具有快速、快速编码、更少的错误、直观、简单、简便、健壮。简易而且本地win10能够跑起来。
二、FastAPI的get接口代码实现
1. 安装: pip install fastapi
pip install uvicorn
2. 代码:
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2019/11/12 21:27
# @author : Mo
# @function: get service of fastapi
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)
浏览器访问结果:
postman访问结果:
三、FastAPI的post接口代码实现
1. 安装: pip install fastapi
pip install uvicorn
2. 代码:
# !/usr/bin/python
# -*- coding: utf-8 -*-
# @time : 2019/11/12 21:27
# @author : Mo
# @function: post service of fastapi
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)
3. 接口访问:http://127.0.0.1:8080/test
postman访问结果:
标签:__,fastapi,app,uvicorn,学习,res,FastAPI
From: https://www.cnblogs.com/wengzx/p/16920360.html