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

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

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

关于python - 使用自定义装饰器/属性记录 Python Bottle API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27850504/

相关文章:

python - scikit-learn MLPRegressor 预测结果总是变化且不一致

c# - 为什么将长度为 0 的 byte[] 注入(inject)到我的类中?

c# - Recaptcha 和 Windows Phone

python - 如何使用plotly修复exe中出现的 "No such file or directory"

python - 删除直线中多余的点

python - 张量 - 定义函数,同时评估另一个函数

asp.net-mvc - 如何保护我的 Web API - MVC4 与 Android/iOS 应用程序

Javascript 手册 : `Array.prototype.includes()` vs. `Array.includes()`

ios - Xcode 5 文档错误

laravel - 如何更改 Larecipe v2.0 Laravel 包中的 Logo ?