Function call using import in web2py

2019-08-08 07:55发布

问题:

I have split the code into multiple files. I have imported all the functions from all other files into admin.py. Lets say I want to call a function XYZ. If I give path to function as admin/XYZ it gives me error as invalid function and for this I have to give the path as file_with_XYZ_function/XYZ.

Is there a way to overcome this problem and simple call all the imported functions from one single file

回答1:

NOTE: This might not be answering your question as I'm not sure I understand your question...

But if you want to put some code into a (shared) module and include it from several of your controllers I suggest that you have a look at chapter four (The Core) of the web2py book and search for local_import.

For this kind of situation, web2py provides another way to import modules in such a way that the global sys.path is not altered: by placing them in the "modules" folder of an application. One side benefit is that the module will be automatically copied and distributed with the application; however, there are certain restrictions that apply. web2py provides a local_import function that must be used to import modules from the "modules" folder.

The import of modules depends on the modules and where web2py can find them. If it is a standard module which web2py can find in sys.path or in web2py/site-packages import modulename should work as expected.

For modules local to your app web2py offers something else: applications/appname/modules

Those modules can be imported using local_import.

mymodule = local_import(themodule)

This imports the module with the name themodule in the apps local modules folder and makes it available under the name mymodule. Note that local_import supports two additional arguments: reload and app. During development module code often changes so don't forget to tell web2py to reload the module upon each request with the parameter reload=True, otherwise you won't see your changes unless you restart web2py.



回答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. now you can use your functions by calling their name

myFunction