1

I have 2 separate controllers and I need import a function from one controller to the other.

For example, I have a.py and b.py, in b.py I have tried:

import a
from applications.a.modules import a
import applications.a.modules.othermodule

I cannot seem to get anything to work after having looked at the documentation as well: http://web2py.com/book/default/chapter/04#Cooperation

How do I import one a function from one controller to another controller?

William Ross
  • 3,568
  • 7
  • 42
  • 73
  • Is a.py in the /controllers folder or the /modules folder of the app? – Anthony Nov 22 '17 at 18:09
  • They are in the controllers folder. Is the modules folder the same as models? My understanding was if they are in models then it's similar to global space. Is there any way to keep the file in the controllers folder and access it from another controller? – William Ross Nov 23 '17 at 15:28
  • No, the /modules folder is not the same as /models. The /modules folder is intended as a place to store app-specific Python modules -- you import them as needed. The /models folder contains Python files that get executed in a web2py environment automatically on each HTTP request. – Anthony Nov 24 '17 at 01:58

1 Answers1

2

In web2py, controllers are not meant to be treated like Python modules and imported in other controllers. Technically you can do that (make sure there is an __init__.py file in the /controllers directory), but controller files are meant to be executed per HTTP request in a web2py environment. If you import a function from a controller, calling the function may not work properly because it may reference web2py environment objects (e.g., request, session, objects defined in model files) that will not be available in the context of the import.

If you want to share functionality between controllers, you are much better off moving the shared functionality to a Python module and importing it in each controller that needs it.

Anthony
  • 25,466
  • 3
  • 28
  • 57