Cleaning up web2py my controllers

末鹿安然 提交于 2019-12-10 04:09:57

问题


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


回答1:


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.



回答2:


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



来源:https://stackoverflow.com/questions/6810282/cleaning-up-web2py-my-controllers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!