Python - how to refer main app's variable in app's modules
Question: I have following files' structure for Flask app (/env is virtual env):

    
    
    /env
    /env/bin/...
    /env/include/...
    /env/lib/...
    /env/lib64/...
    /env/myapp.py
    /mymodules/__init__.py
    /mymodules/users/__init__.py
    /mymodules/users/controller.py
    

myapp.py has below content:

    
    
    # -*- coding: utf-8 -*-
    
    from flask import Flask
    from flask import request, current_app
    from flask.ext.sqlalchemy import SQLAlchemy
    import mymodules.users.controller as MyMods
    
    
    app = Flask(__name__)
    
    db = SQLAlchemy(app)
    
    # [...]
    
    @app.route(u"/test", methods=['GET'])
    def test():
    
        return MyMods.mytest()
    
    if __name__ == u"__main__":
        app.run()
    

Content of controller.py

    
    
    # -*- coding: utf-8 -*-
    
    def mytest():
        return "ok"
    

Question: how can I use `app` and `db` inside controller.py?

I can pass it as param:

    
    
    MyMods.mytest(app, db)
    
    def mytest(app_ref, db_ref):
    

but is it the proper way of doing it?


Answer: You can pass it param as you did or could set module level variables:

    
    
    # controller.py
    some_var = None
    def mytest():
        print(some_var)
    
    # myapp.py
    MyMods.some_var = db
    ...rest of your code...
    

As long as `some_var` gets set before `mytest()` gets called.

