python3写一个http接口服务(get, post),给别人调用6
一、python3写一个http接口服务(get, post),给别人调用6
近年来异步web服务器比较火热,例如falcon/bottle/sanic/aiohttp,今天也来玩玩sanic。
Sanic是一个支持Python 3.7+的web服务器和web框架,速度很快。它允许使用Python 3.5中添加的async/await语法,无阻塞且快。
Sanic也符合ASGI,目标是提供一种简单的方法来建立和运行一个高性能的HTTP服务器,该服务器易于构建、扩展。
二、FastAPI的get接口代码实现
2.1 安装
pip install sanic
2.2 代码
# -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2022/2/22 21:43
# @author :Mo
# @function :get/post of sanic
from sanic.response import json, text
from sanic import Sanic, request
app = Sanic("calculate")
app.config.HEALTH = True
@app.route("/calculate/add", methods=["GET", "POST"])
async def calculate_add(request):
""" 分类 """
if request.method == "POST":
params = request.form if request.form else request.json
elif request.method == "GET":
params = request.args
else:
params = {}
a = params.get("a", 0)
b = params.get("b", 0)
c = int(a) + int(b)
data_dict = {"c": c}
status_code = 200
res_dict = {"code": status_code,
"data": data_dict,
"message": "success"
}
return json(res_dict, status=status_code, ensure_ascii=False)
if __name__ == "__main__":
app.run(single_process=True,
access_log=True,
host="0.0.0.0",
port=8032,
workers=1,
)
2.3 接口访问
2.3.1 GET接口
GET请求: http://localhost:8032/calculate/add?a=1&b=1
请求结果:
2.3.2 POST接口
POST请求: http://localhost:8032/calculate/add
Body: {“a”:618, “b”: 32}
请求结果:
三、参考
-
https://github.com/sanic-org/sanic
-
https://github.com/sanic-org/sanic
希望对你有所帮助