使用自定义装饰器/属性记录Python瓶API

使用自定义装饰器/属性记录Python瓶API,python,documentation,asp.net-web-api,bottle,Python,Documentation,Asp.net Web Api,Bottle,我正在开发一个API(使用Python瓶子框架),它将被各种客户机使用。在这样做的过程中,我试图在文档方面一举两得。我想做的是创建某种类型的装饰器/属性,在这里我可以描述API的每个公共路由。然后,我有一个路由,它在所有其他路由中循环,并收集这些信息(描述、输入、输出…)。此信息以JSON数组的形式返回,并以用户友好的html格式呈现 收集路线信息很容易: @route('/api-map',method=['GET']) def api_map(): api_methods = []

我正在开发一个API(使用Python瓶子框架),它将被各种客户机使用。在这样做的过程中,我试图在文档方面一举两得。我想做的是创建某种类型的装饰器/属性,在这里我可以描述API的每个公共路由。然后,我有一个路由,它在所有其他路由中循环,并收集这些信息(描述、输入、输出…)。此信息以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

关于如何实施这一方法有何建议?我不知道这样的东西已经存在了吗?

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

瓶装0_模板.第三方物流

<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>
然后转到
http://localhost:8080/api-文件

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)