2015-01-08 90 views
2

我正在研究將由各種客戶端使用的API(使用Python Bottle框架)。在這樣做的過程中,我試圖用文檔來扼殺兩隻鳥。我想要做的是創建一些類型的裝飾器/屬性,我可以在其中描述API的每個公共路由。然後,我有一條路徑遍歷所有其他路徑,並收集這些信息(描述,輸入,輸出...)。這些信息以JSON數組的形式返回 - 它以用戶友好的html格式呈現。使用自定義裝飾器/屬性記錄Python Bottle API

收集的路由信息​​很簡單:

@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 

就如何落實這種做法有什麼建議?像這樣的東西已經存在,我不知道?

回答

2

我會用正常的文檔字符串,並創建一個模板來渲染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 "[email protected]#!#[email protected]#" 

@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) 

then go to http://localhost:8080/api-doc