views:

97

answers:

2

In web2py, is there a way to 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 mecanisms. In the same breath, I'm curious to know if other MVC frameworks have found any interesting ways of dealing with this.

Thank you

Mark

+3  A: 

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.

RedGlyph
+1  A: 

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.

Thadeus