【问题标题】:Documenting Python Bottle API With Custom Decorators/Attributes使用自定义装饰器/属性记录 Python Bottle API
【发布时间】:2015-01-08 22:15:14
【问题描述】:

我正在开发一个可供各种客户端使用的 API(使用 Python Bottle 框架)。在这样做的过程中,我试图用一块石头杀死 2 只鸟。我想做的是创建某种类型的装饰器/属性,我可以在其中描述 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

关于如何实施这种方法的任何建议?是否已经存在我不知道的类似情况?

【问题讨论】:

    标签: python documentation asp.net-web-api bottle


    【解决方案1】:

    我会使用普通的文档字符串并创建一个模板来以可读的方式呈现您的 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

    【讨论】:

      猜你喜欢
      • 2018-07-20
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多