How to import _ from flask_babel without throwing key error

674 views Asked by At

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:-

  • The sub module imports _ from flask_babel.
  • The parent module imports a class Result from the sub module.
  • The parent module used to work, all I changed was move the sub module to a sibling directory.
  • The sub module works fine if I run it directly, _ works.
  • The sub module throws a key error during import when I run the parent module.
  • The key error occurs looking for 'babel' in the dictionary msglib.
  • If I replace _ with my own function everything works.

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?

1

There are 1 answers

0
Mark Kortink On BEST ANSWER

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)