一、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)
3. 接口访问:
浏览器访问结果:
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. 接口访问:
postman访问结果:
————————————————
版权声明:本文为CSDN博主「大漠帝国」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/rensihui/java/article/details/103038869
阅读(18055) | 评论(0) | 转发(0) |