在web2py中,有一个方法有一块共同的代码被称为所有控制器之前被执行?

例如,我想添加一些代码,将记录客户IP地址到一个日志请求,使分析。我可以简单地让我的所有控制器的第一行是这样的response = RequestBase(request)但我很好奇,想知道这是否是包括已经通过一些其他机制解决的问题。

有帮助吗?

解决方案

您可以简单地把你的日志代码块模型定义文件,models/db.py,或在您的控制器controllers/default.py这样的:

with open("mylog.log", "at") as f:
    f.write(repr(request))

def index():
    # index controller definition

# ... rest of the code

或者,如果需要来定义函数或类:

# --------------------------
# Log part:
# --------------------------

def my_log(request):
    with open("mylog.log", "at") as f:
        f.write(repr(request))

my_log(request)

# --------------------------
# Controllers part:
# --------------------------

def index():
    # index controller definition

# ... rest of the code

当然,repr(request)是不是你想要的,但你的想法。从那里你可以记录任何信息,你喜欢被称为控制器之前(他们在这个阶段刚刚定义)

在服务器已经维护日志中的根目录下,在httpserver.log

其他提示

放置在模型文件中的代码,它将任何控制器之前得到执行。如果您只想要执行的代码为特定的控制器,将其放置在控制器之前的任何功能上。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top