2016-01-21 109 views
0

我使用bottle.route()到HTTP查詢重定向到適當的功能如何預處理所有呼叫?

import bottle 

def hello(): 
    return "hello" 

def world(): 
    return "world" 

bottle.route('/hello', 'GET', hello) 
bottle.route('/world', 'GET', world) 
bottle.run() 

我想一些預處理添加到每個呼叫,即在所述源IP(通過bottle.request.remote_addr獲得)行動的能力。我可以指定每條路徑中的預處理

import bottle 

def hello(): 
    preprocessing() 
    return "hello" 

def world(): 
    preprocessing() 
    return "world" 

def preprocessing(): 
    print("preprocessing {ip}".format(ip=bottle.request.remote_addr)) 

bottle.route('/hello', 'GET', hello) 
bottle.route('/world', 'GET', world) 
bottle.run() 

但這看起來很尷尬。

有沒有一種方法可以在全球範圍內插入預處理功能?(?讓每個呼叫轉到雖然它)

+2

如何使用裝飾 – realli

+0

@realli:不會是差不多相同(每個函數一個裝飾器,類似於我的'preprocessing()'調用)? – WoJ

+0

是的,試試瓶子的插件http://bottlepy.org/docs/dev/plugindev.html#bottle.Plugin – realli

回答

4

我認爲你可以使用瓶子的插件

DOC這裏:http://bottlepy.org/docs/dev/plugindev.html#bottle.Plugin

代碼示例

import bottle 

def preprocessing(func): 
    def inner_func(*args, **kwargs): 
     print("preprocessing {ip}".format(ip=bottle.request.remote_addr)) 
     return func(*args, **kwargs) 
    return inner_func 

bottle.install(preprocessing) 

def hello(): 
    return "hello" 


def world(): 
    return "world" 

bottle.route('/hello', 'GET', hello) 
bottle.route('/world', 'GET', world) 
bottle.run()