Python 如何预处理所有呼叫?

Python 如何预处理所有呼叫?,python,bottle,Python,Bottle,我使用battle.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进行操作的能力(通过battle.request.re

我使用
battle.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进行操作的能力(通过
battle.request.remote\u 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()
但这看起来很尴尬


有没有一种方法可以在全局级别插入预处理功能?(这样每次调用都可以通过它?

我想你可以使用瓶子的插件

文件在此:

代码示例

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

我想你可以使用瓶子的插件

文件在此:

代码示例

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

使用如何Decorators@realli:这不是差不多吗(每个函数有一个decorator,类似于我的
preprocessing()
call)?是的,试试瓶子的插件使用怎么样Decorators@realli:这不是差不多吗(每个函数有一个decorator,类似于我的
preprocessing()
call)?是的,试试瓶子的插件