Sanic 框架
项目结构同flask定义
sanic 中间件
async def before_request(request):
print('Before request')
return
async def during_request(request):
print('During request')
return
async def after_request(request, response):
print('After request')
return response
代码展示
from sanic import Sanic, NotFound, HTTPResponse
from sanic.response import json
from bson.objectid import ObjectId
from Sanic_Plant.middleware import before_request, during_request, after_request
from utils.mongodb_tool import db
app = Sanic(__name__)
@app.route('/plants')
async def get_all_plants(request):
plants = []
for plant in db.plants.find():
plants.append(plant)
plants = [{k: str(v) for k, v in each_plant.items()} for each_plant in plants]
return json(plants)
@app.route('/plant/<o_id:str>')
async def get_one_plant(request, o_id):
if not o_id:
return HTTPResponse("请求数据有误", status=400)
plant = db.plants.find_one({"_id": ObjectId(o_id)})
if not plant:
return HTTPResponse("未找到植物数据", status=400)
plant['_id'] = str(plant['_id'])
return json(plant)
@app.route('/plant/add', methods=['POST'])
async def add_plant(request):
plant_data = request.json
print(plant_data, type(plant_data))
result = db.plants.insert_one(plant_data)
return json({
"inserted_id": str(result.inserted_id),
"method": "add",
"message": "新增成功!"
})
@app.route('/plant/edit/<o_id:str>', methods=['PUT'])
async def put_plant(request, o_id):
if not o_id:
return HTTPResponse("请求数据有误", status=400)
plant_data = request.json
plant = db.plants.find_one({"_id": ObjectId(o_id)})
if not plant:
return HTTPResponse("未找到植物数据", status=400)
result = db.plants.update_one({"_id": ObjectId(o_id)}, {"$set": plant_data})
return json({
"upserted_id": str(result.upserted_id or '') or '',
"method": "update",
"message": "修改成功!"
})
@app.route('/plant/delete/<o_id:str>', methods=['delete'])
async def delete_plant(request, o_id):
if not o_id:
return HTTPResponse("请求数据有误", status=400)
plant = db.plants.find_one({"_id": ObjectId(o_id)})
if not plant:
return HTTPResponse("未找到植物数据", status=400)
result = db.plants.delete_one({"_id": ObjectId(o_id)})
return json({
"deleted_count": str(result.deleted_count),
"method": "delete",
"message": "删除成功!"
})
app.register_middleware(before_request, "request")
app.register_middleware(during_request, "request")
app.register_middleware(after_request, "response")
if __name__ == '__main__':
app.run('127.0.0.1', port=9001)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?