[python3] tornado 使用swagger编写接口文档

  • python3.12

  • tornado 6.1

  • swagger 1.2.3

    pip install tornado-swagger==1.2.3

示例代码

python 复制代码
import tornado.ioloop
import tornado.web
from tornado_swagger.setup import setup_swagger


class ItemHandler(tornado.web.RequestHandler):
    def get(self, item_id):
        """
        ---
        tags:
          - Items
        summary: Get an item by ID
        description: Retrieve item details by its ID
        parameters:
          - name: item_id
            in: path
            required: true
            description: ID of the item
            type: integer
        responses:
          200:
            description: Successful operation
            schema:
              type: object
              properties:
                name:
                  type: string
                price:
                  type: number
          404:
            description: Item not found
        """
        item = {"name": "ExampleItem", "price": 99.99}
        print('item_id: ', item_id)
        if int(item_id) == 1:
            self.write(item)
        else:
            self.write({"error": "Item not found"})


def make_app():
    routes = [
        tornado.web.url(r"/item/([0-9]+)", ItemHandler),
    ]
    setup_swagger(routes, swagger_url="/api/doc",
                  description="使用 setup_swagger 设置 Swagger 文档")
    return tornado.web.Application(routes)


if __name__ == "__main__":
    app = make_app()
    app.listen(38881)
    tornado.ioloop.IOLoop.current().start()

浏览器打开

http://IP:38881/api/doc

相关推荐
星期天要睡觉几秒前
深度学习——基于 PyTorch 的蔬菜图像分类
人工智能·pytorch·python·深度学习·分类
蒋星熠14 分钟前
Python爬虫抓取豆瓣TOP250数据
人工智能·爬虫·python·网络爬虫·爬山算法
scala舔狗汪42 分钟前
python的表白浪漫
python
墨尘笔尖1 小时前
使用子进程实现 C++ 与 Python 交互式控制台
c++·windows·python
码界筑梦坊1 小时前
74-基于Python的蜜雪冰城门店数据可视化分析系统
python·数据分析·flask·毕业设计
风亦辰7391 小时前
从 Hello World 到游戏世界——pygame 快速入门
python·游戏·pygame
程序员爱钓鱼3 小时前
Python编程实战 · 基础入门篇 | 类型转换与输入输出
后端·python
程序员爱钓鱼3 小时前
Python编程实战 · 基础入门篇 | 运算符详解
后端·python·编程语言
潜心编码3 小时前
基于Flask的志愿者管理系统
后端·python·flask
开心-开心急了3 小时前
Flask入门教程——李辉 第四章 静态文件 关键知识梳理 更新1次
后端·python·flask