python - Flask app.before_request is not working when it moved to other module -
i'm learning flask these days.
at first, wrote whole codes in main.py
, , started split codes code increase.
everything ok. @app.before_request
worked when in main.py
, stopped working after move code separate module.
i spent many hours catch reason, imagined yet. :(
main.py
here
app = flask(__name__) app.config.from_object(settings) db = sqlalchemy() @app.before_request def working(): 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 main import app user.models import user @app.before_request def not_working(): print '### called in frontend.helpers ###' g.user = user.get_by_session()
the result shows @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 work well?
if running main.py
main entry script command line, whole namespace of module stored in __main__
module, not main
module. why if __name__ == '__main__'
test succeeds.
however, frontend/helpers.py
module imports main
, far python concerned, different module. created two distinct flask
instances, each living in different module namespace.
in other words, __main__.app
being used run flask server, before_request
hook registered different, separate main.app
object.
don't use same module run script , create flask
wsgi object. use separate module this. don't try use from __main__ import app
that'll break when deploy wsgi container gunicorn
or mod_wsgi
.
Comments
Post a Comment