pythonflask-babel

How to import _ from flask_babel without throwing key error


I am importing a sub module into a parent module and getting a key error.

The sub module code (pruned) is as follows.

from flask_babel import _
#def _(intext): return intext

... code ...
class Result:
... code ...

msglib = {

        'ok': 
            _('Success'),
            
        ...
        }

The error message is: -

Exception has occurred: KeyError 'babel' File "C:...\solution\cradle\messaging.py", line 196, in >> _('Success :)'), File "C:\Users\Mark Kortink\OneDrive\dev\metapplica_dev\entity_frame.py", line 15, in from solution.cradle.messaging import Result

The pertinent facts are:-

This is bizarre behaviour to me, I cannot understand why 'babel' is being searched for during import in the first place. Moving the sub module should have made no difference because I changed associated imports. Providing my own _ does not trigger the error so there cannot be a search for 'babel' in this case???

Can anyone suggest what may be going on here?


Solution

  • My Flask app uses the Babel extension. Close inspection of the following error messages implies that the key error is occurring within the Babel code not my code.

      File "C:\Users\Mark Kortink\OneDrive\dev\metapplica\venv\lib\site-packages\flask_babel\__init__.py", line 548, in gettext
        t = get_translations()
      File "C:\Users\Mark Kortink\OneDrive\dev\metapplica\venv\lib\site-packages\flask_babel\__init__.py", line 217, in get_translations     
        **babel = current_app.extensions['babel']**
    

    My code is running in a playpen environment that I have to initialise for Flask. Although I don't fully understand the problem it is to do with pushing application context and adding the following code to my initialisation script fixed the problem.

    from flask_babel import Babel
    
    babel = Babel()
    babel.init_app(app)