[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

相关推荐
站大爷IP几秒前
Python 办公实战:用 python-docx 自动生成 Word 文档
python
MO2T26 分钟前
使用 Flask 构建基于 Dify 的企业资金投向与客户分类评估系统
后端·python·语言模型·flask
慢热型网友.29 分钟前
用 Docker 构建你的第一个 Python Flask 程序
python·docker·flask
Naiva29 分钟前
【小技巧】Python + PyCharm 小智AI配置MCP接入点使用说明(内测)( PyInstaller打包成 .exe 可执行文件)
开发语言·python·pycharm
云动雨颤33 分钟前
Python 自动化办公神器|一键转换所有文档为 PDF
运维·python
梅孔立1 小时前
yum update 报错 Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64 等解决办法
linux·python·centos
前端付豪1 小时前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
这里有鱼汤1 小时前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
源码站~1 小时前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo1 小时前
Python 爬虫实战 | 国家医保
python