python快速构建http服务

前提条件

pip install fastapi
 pip install uvicorn

构建http get服务

# !/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)

接口访问:http://127.0.0.1:8080/test/a=1/b=4

构建http post服务

# !/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)

只能使用postman请求
设置body为
{
“a”:1.
“b”:2
}
即可

参考连接:https://blog.csdn.net/rensihui/article/details/103038869

你可能感兴趣的:(Python学习,服务端学习,python,http,lua)