Sanic 框架

Sanic 框架

项目结构同flask定义

sanic 中间件

# 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

代码展示

# -*- coding: utf-8 -*-
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 = list(db.plants.find())  # db中获取数据
    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))
    # mongo 新增一条数据, insert_one
    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)

    # 获取 body 数据
    plant_data = request.json

    # 判断是否存在
    plant = db.plants.find_one({"_id": ObjectId(o_id)})
    if not plant:
        return HTTPResponse("未找到植物数据", status=400)

    # mongodb 更新一条数据 update_one
    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)

    # mongodb 删除一条数据 update_one
    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)

posted @   染指未来  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示