Cleaning up web2py my controllers
Asked Answered
D

2

7

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

Dm answered 24/7, 2011 at 22:51 Comment(1)
It is not clear to me: do you want to have your controllers in different files in the controllers folder, which is perfectly possible and normal, or to have them in a different folder, which AFAIK is not possible.Mackenziemackerel
M
6

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.
Mook answered 25/7, 2011 at 15:16 Comment(1)
I'm not sure. I would think not much. Note, the above pattern is how the framework's Auth, Crud, and Mail systems work.Mook
J
3

you can create python files in modules folder and import them just like how you import python libraries in your controllers. But you have to give the path to those files like

 from applications.myApp.modules.myModule import *

this is my solution for my wrappers

Jelene answered 27/7, 2011 at 14:19 Comment(1)
If the module is in the current application's 'modules' folder, you do not need to specify the full path -- just use the module name by itself. For example, if you have mymodule.py in /applications/myapp/modules, you can just do from mymodule import * from anywhere in the 'myapp' application code.Mook

© 2022 - 2024 — McMap. All rights reserved.