Python 有没有一种方法可以从瓶子路径自动生成RESTAPI JSON描述
如果我有以下代码:Python 有没有一种方法可以从瓶子路径自动生成RESTAPI JSON描述,python,json,rest,bottle,Python,Json,Rest,Bottle,如果我有以下代码: 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)
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?>
class MyApp():
定义初始化(自):
self.bottle=bottle()
self.battle.route('/')(self.show_api)
self.battle.route('/api/')(self.show_api)
self.battle.route('/api/item',method='PUT')(self.save_item)
def显示api(自身):
返回
可以从中获得JSON格式的RESTAPI文档吗?
出于某种原因,self.battle.routes没有返回任何有用的内容
谢谢 用于装饰:
@app.route('/hello/:name')
def hello(name):
return 'Hello %s' % name
所以它确实返回了一些有用的东西:修饰函数
然后,您可以使用app.routes
获取已声明路线的列表
print(app.routes)
输出:
[<GET '/hello/:name' <function hello at 0x7f4137192e18>>]
[]
函数不能直接进行JSON序列化。但是您可以很容易地使用
str
获得字符串表示。实际上,生成JSON API描述的正确方法似乎是:
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)
我的代码中有一个错误,我希望它在浏览器窗口中返回路由列表,但由于输出使它看起来没有任何有用的内容,所以返回了。当然,当我打印时,我会看到函数。