清理 web2py 我的控制器
我的 web2py 应用程序中的控制器变得有点混乱,我想将功能移到另一个地方。
我最初考虑将它们移动到模块,但我有时会访问数据库,并在 db.py 中设置其他参数(我是用户 ID,现在是日期等)。
有没有一种干净的方法可以将这些函数移动到新文件,同时仍然可以访问我需要的变量?我不反对 from db import me, now
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的控制器操作(即,出现在 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
, andnow
objects to those functions as arguments. Another option is to add them to the thread localcurrent
object, which can be accessed from modules. To do so:In a model:
In a module:
您可以在模块文件夹中创建 python 文件并导入它们,就像在控制器中导入 python 库一样。但是你必须给出这些文件的路径,就像
这是我的包装器的解决方案
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
this is my solution for my wrappers