2013-08-18 24 views
5

假設我在/ api/something處有一個API。 API需要api_key的定義,它會查找請求參數和cookie。如果它找到api_key,我希望它將api_key傳遞給路由方法,在這種情況下爲somethingFlask添加參數以查看before_request中的方法

@app.before_request 
def pass_api_key(): 
    api_key = request.args.get('api_key', None) 
    if api_key is None: 
     api_key = request.cookies.get('api_key', None) 
    if api_key is None: 
     return 'api_key is required' 
    # add parameter of api_key to something method 

@app.route('/api/something') 
def something(api_key): 
    return api_key 

這可能嗎?

在此先感謝。

回答

8

要做到這一點的一種方法是使用flask.g。從the docs

要共享僅對一個請求有效的數據從一個函數到另一個函數,全局變量不夠好,因爲它會在線程化環境中中斷。 Flask爲您提供一個特殊對象,確保它僅對活動請求有效,並且會爲每個請求返回不同的值。

g.api_key設置爲您想要存儲在before_request中的值並在路徑方法中讀出它。

0

這可以通過使用url_value_processor裝飾來完成:

@app.url_value_preprocessor 
def get_project_object(endpoint, values): 
    api_key = values.get('api_key') 
    if api_key is None: 
     api_key = request.cookies.get('api_key', None) 
    if api_key is None: 
     raise Exception('api_key is required') 
    values['api_key'] = api_key 

這也可以在一個藍圖的基礎上完成,所以它僅適用於在指定藍圖的意見。