有没有一种方法可以从Bottle路由自动生成REST API JSON描述 [英] Is there a way to automatically generate REST API JSON description from Bottle routes

查看:92
本文介绍了有没有一种方法可以从Bottle路由自动生成REST API JSON描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有此代码:

class MyApp():
    def __init__(self):
        self.bottle = Bottle()
        self.bottle.route('/')(self.show_api)
        self.bottle.route('/api/')(self.show_api)
        self.bottle.route('/api/item', method='PUT')(self.save_item)

    def show_api(self):
        return <JSON representation of the API?>

是否可以从中获取JSON格式的REST API文档? 由于某些原因,self.bottle.routes没有返回任何有用的信息.

Is it possible to get a REST API documentation in JSON format from that? fro some reason self.bottle.routes didn't return anything useful.

谢谢!

推荐答案

实际上,生成JSON API描述的正确方法似乎是:

Actually the right way to generate the JSON API description seems to be:

from collections import defaultdict
import json

def show_api(self):
    api_dict = defaultdict(dict)

    for route in self.bottle.routes:
        api_dict[route.rule]['url'] = 'http://myhost:port{}'.format(route.rule)
        api_dict[route.rule]['method'] = route.method

        # additional config params
        for key in route.config:
            api_dict[route.rule][key] = route.config[key]

    return json.dumps(api_dict)

这篇关于有没有一种方法可以从Bottle路由自动生成REST API JSON描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆