清理 web2py 我的控制器 [英] Cleaning up web2py my controllers
问题描述
我的 web2py 应用程序中的控制器有点混乱,我想将功能移到另一个地方.
My controllers are getting a bit cluttered in my web2py app, and I would like to move functions to another place.
我最初想将它们移动到模块中,但有时我会访问数据库,并且在 db.py 中设置了其他参数(我是用户 ID,现在是日期等).
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.).
是否有一种干净的方法可以将这些函数移动到新文件,同时仍然可以访问我需要的变量?我不反对像 from db import me, now
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
推荐答案
您的控制器操作(即出现在 URL 中的操作)必须是在控制器文件中定义的函数(即,您不能将它们移动到模块中).但是,如果您的控制器中有不是动作的功能,您可以将它们移动到模块中.假设您将从模型或控制器调用这些函数,您只需将 db
、me
和 now
对象作为参数传递给这些函数.另一种选择是将它们添加到线程本地 current
对象中,该对象可以从模块访问.这样做:
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:
在模型中:
from globals import current
current.app.db = db
# etc.
在模块中:
from globals import current
def func(*args):
db=current.app.db
# etc.
这篇关于清理 web2py 我的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!