开发者

web2py: How can I execute code before calling the controllers?

开发者 https://www.devze.com 2022-12-11 07:03 出处:网络
In web2py, is there a way t开发者_高级运维o have a piece of common code be executed before all controllers are called?

In web2py, is there a way t开发者_高级运维o have a piece of common code be executed before all controllers are called?

For example, I want to add some code that will log client IPs to a log of requests to enable analysis. I could simply make the first line of all my controllers be something like response = RequestBase(request) but I'm curious to know if this is a problem that's already been solved through some other mechanisms.


You could simply put your piece of logging code in the model definition file, models/db.py, or in your controller controllers/default.py like this:

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

def index():
    # index controller definition

# ... rest of the code

or, if you need functions or classes to be defined:

# --------------------------
# 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

Of course, repr(request) is not how you want it, but you get the idea: from there you can log any information you like before the controllers are called (they are just defined at this stage).

The server already maintains a log in the root directory, in httpserver.log.


Place the code in a model file and it will get executed before any controllers. If you only want the code to execute for a specific controller, place it at the top of the controller before any functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消