Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask app.before_request is not working when it moved to other module

Tags:

python

flask

I'm learning Flask these days.

At first, I wrote whole codes in main.py, and started to split codes as code increase.

Everything was OK. But @app.before_request worked well when it in main.py, but stopped working after move this code into a separate module.

I spent many hours to catch the reason, but even imagined yet. :(

main.py is here

app = Flask(__name__)
app.config.from_object(settings)
db = SQLAlchemy()


@app.before_request
def working():
    from user.models import User
    print '### called in main ###'
    g.user = User.get_by_session()


if __name__ == '__main__':
    db.init_app(app)
    app.register_blueprint(frontend.views.blueprint)
    app.register_blueprint(user.views.blueprint)
    import frontend.helpers
    app.run()

and frontend/helpers.py

from flask import g
from main import app
from user.models import User

@app.before_request
def not_working():
    print '### called in frontend.helpers ###'
    g.user = User.get_by_session()

The result shows that @app.before_request in frontend/helpers.py not called.

127.0.0.1 - - [30/Sep/2015 15:55:35] "GET /login HTTP/1.1" 200 -
### called in main ###

How can I do this to work well?

like image 413
Lee Kwangyoung Avatar asked Oct 16 '25 20:10

Lee Kwangyoung


1 Answers

If you are running main.py as the main entry script from the command line, then the whole namespace of the module is stored in the __main__ module, not the main module. This is also why the if __name__ == '__main__' test succeeds.

However, your frontend/helpers.py module imports from main, which as far as Python is concerned, a different module. You now created two distinct Flask instances, each living in a different module namespace.

In other words, __main__.app is being used to run your Flask server, but your before_request hook is registered with a different, separate main.app object.

Don't use the same module to run as a script and to create the Flask WSGI object. Use a separate module for this. Don't try to use from __main__ import app as that'll break when you deploy as to a WSGI container like gunicorn or mod_wsgi.

like image 51
Martijn Pieters Avatar answered Oct 18 '25 08:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!