Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up web2py my controllers

Tags:

web2py

My controllers are getting a bit cluttered in my web2py app, and I would like to move functions to another place.

I was initially thinking of moving them to modules, but I access the db sometimes, and have other parameters set in db.py (me for user id, now for the date, etc.).

Is there a clean way to move these functions to a new file while still having access to the variables I need? I'm not opposed to something like from db import me, now

like image 844
Charles L. Avatar asked Jul 24 '11 22:07

Charles L.


1 Answers

You controller actions (i.e., the actions that appear in URLs) have to be functions defined in a controller file (i.e., you cannot move them to a module). However, if there are functions in your controller that are not actions, you may move those to a module. Assuming you will call those functions from a model or controller, you can simply pass your db, me, and now objects to those functions as arguments. Another option is to add them to the thread local current object, which can be accessed from modules. To do so:

In a model:

from globals import current
current.app.db = db
# etc.

In a module:

from globals import current

def func(*args):
    db=current.app.db
    # etc.
like image 167
Anthony Avatar answered Sep 19 '22 22:09

Anthony