i have problem with out of context for session in flask

48 Views Asked by At

i wrote multiple languages panel with flask and flask-babel and set lang in session for detect languages and load content and i use factory pattern for create app. now i want to use session out of context of my app to set locale for babel

def get_locale():
   if session.get("lang", False):
       session["lang"] = "fa"
   return session["lang"]

babel = Babel()


def create_app(config_name: str = 'dev') -> Flask:
    app = Flask(__name__, static_url_path='/assets')

    app.config.from_object(cfg[config_name])

    with app.app_context():
        babel.init_app(app, locale_selector=get_locale)

    return app

i tried g but its not working in every request g is empty

2

There are 2 best solutions below

2
IkonoDim On

Try using cookies. I dont think that flasks session-system is reachable from the Frontend. This worked for me quite well.

0
Carmelot On

I think you dont need to use "with app.app_context()" when initializing babel.