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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With