Cleaning web2py of my controllers

My controllers get a little clogged in my web2py application, and I would like to move the functions to another place.

At first I thought about porting them to modules, but sometimes I access db and have other parameters set in db.py (for user ID, now for date, etc.).

Is there a clean way to move these functions to a new file, having access to the variables that I need? I don't mind something like from db import me, now

+6
source share
2 answers

Controller actions (i.e. actions displayed in URLs) must be functions defined in the controller file (i.e. you cannot move them to a module). However, if the controller has functions that are not actions, you can transfer them to the module. Assuming you call these functions from a model or controller, you can simply pass the db , me and now objects for these functions as arguments. Another option is to add them to the local current stream object, which can be accessed from the modules. For this:

In the model:

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

In the module:

 from globals import current def func(*args): db=current.app.db # etc. 
+6
source

you can create python files in the modules folder and import them the same way you import python libraries into your controllers. But you must specify the path to the files, for example

  from applications.myApp.modules.myModule import * 

this is my solution for my wrappers

+3
source

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


All Articles