[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

相关推荐
codists18 分钟前
《Grokking Concurrency》读后感
python
坤岭29 分钟前
Python内存溢出问题
python
三木彤30 分钟前
Python 反爬 UA 检测真实案例(3个典型场景,可复现、合法合规)
python
SCBAiotAigc30 分钟前
MinerU离线推理
人工智能·python·mineru
94620164zwb531 分钟前
关于应用模块 Cordova 与 OpenHarmony 混合开发实战
python·学习
趁月色小酌***31 分钟前
JAVA 知识点总结5
java·开发语言·python
natide1 小时前
表示/嵌入差异-1-欧几里得距离(Euclidean Distance)-L2 距离(L2 distance)-欧式距离的标准化
人工智能·pytorch·python·深度学习·算法·自然语言处理
对方正在长头发丿1 小时前
Numpy学习篇
python·学习·jupyter·pycharm·numpy
Elaine3361 小时前
深度实战:基于 Scrapy CrawlSpider 的全自动化教程采集系统
python·scrapy·自动化·网络爬虫
2401_841495641 小时前
【游戏开发】登山赛车
数据结构·python·游戏·游戏开发·pygame·登山赛车游戏·游戏打包发布