Skip to main content
 首页 » 编程设计

python之使用自定义装饰器/属性记录 Python Bottle API

2024年10月25日16lovecherry

我正在开发一个将被各种客户端使用的 API(使用 Python Bottle 框架)。在这样做时,我试图用一 block 石头杀死两只鸟关于文档。我想做的是创建某种类型的装饰器/属性,我可以在其中描述 API 的每个公共(public)路由。然后,我有一个循环遍历所有其他路由的路由,并收集这些信息(描述、输入、输出……)。此信息作为 JSON 数组返回 - 它以用户友好的 html 格式呈现。

收集路线信息很容易:

@route('/api-map',method=['GET']) 
def api_map(): 
    api_methods = [] 
    for route in app.routes: 
        if route.rule != "/api-map": 
            ##TODO: get custom attribute from routes function with description, inputs, outputs... 
            api_methods.append({"route":route.rule,"desc":"?"}) 
 
    response.content_type = 'application/json' 
    return {"apiMap":api_methods} 

但我对如何实现文档感到困惑。下面是我试图实现的概念,其中“svmdoc”是我放置此信息的属性:

@route('/token',method=['GET']) 
@svmdoc(desc="Generates Token",input="username and password") 
def getToken(): 
    #TODO token magic 

关于如何实现这种方法有什么建议吗?是否已经存在我不知道的类似情况?

请您参考如下方法:

我会使用普通的文档字符串并创建一个模板以可读的方式呈现您的 api 文档

bottle0_template.tpl

<table> 
<tr style="background-color:#CCCFDF"><th colspan="2">API Documentation</th></tr> 
<tr style="background-color:#CCCFDF"><th>ENDPOINT</th><th>DESC</th></tr> 
 % for color,resource in zip(colors,routes) : 
   % docx = resource.callback.__doc__.replace("\n","<br/>") 
   <tr style="background-color:{{ color }}"><td>{{ resource.rule }}</td><td> {{! docx }} </td></tr> 
 % end 
 </table> 

然后把你的文件改成

bottle0.py

from bottle import route, run,app,template 
from itertools import cycle 
docs_exclude = "/api-doc","/api-map" 
 
@route('/api-doc',method=['GET']) 
def api_doc(): 
    colors = cycle('#FFFFFF #CCCFDF'.split()) 
    routes = filter(lambda x:x.rule not in docs_exclude,app[0].routes) 
    return template("bottle0_template",colors=colors,routes=routes) 
 
 
@route('/token') 
def token(): 
    ''' 
    grant api token 
 
    params: 
      username: string,username of user 
      password: string, password of user 
    ''' 
    return "ASD!@#!#!@#" 
 
@route('/userinfo') 
def userinfo(): 
    ''' 
    grant api token 
 
    params: 
      - username: string,username of user to retrieve data for 
      - code: string, api access token 
    ''' 
    return json.dumps({"name":"bob"}) 
 
#print app[0].routes[1].callback.__doc__#api-doc 
run(host='localhost', port=8080, debug=True) 

然后转到http://localhost:8080/api-doc