2016-01-21 69 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()