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

In web2py, is there a way for some of the shared code to execute before all controllers are called?

For example, I want to add code that will write client IP addresses to the query log to enable analysis. I could just make the first line of all my controllers something like response = RequestBase(request), but I'm curious to know if this is a problem that has already been solved with some other mechanisms.

+3
source share
2 answers

You can simply put your piece of registration code in the model definition file, models/db.pyor in your controller controllers/default.pyas follows:

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 that need 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)this is not how you want it, but you get the idea: from there you can record any information that you like before calling the controllers (they are simply defined at this stage).

The server already supports logging in the root directory, in httpserver.log.

+3
source

Put the code in the model file and it will run in front of any controllers. If you want the code to run for a specific controller, place it at the top of the controller before any functions.

+3
source

Source: https://habr.com/ru/post/1722950/


All Articles