python - Import statement flow -


my app layout

my_app     __init__.py      my_app         __init__.py         startup             __init__.py             create_app.py             create_users.py             common_settings.py         core             __init__.py             models.py             views.py         errors             __init__.py             errors.py 

inner __init__.py

from flask import flask flask_script import manager flask_sqlalchemy import sqlalchemy  app = flask(__name__)           # wsgi compliant web application object db = sqlalchemy(app)            # setup flask-sqlalchemy manager = manager(app)          # setup flask-script  my_app.startup.create_app import create_app create_app() 

create_app.py

def create_app(extra_config_settings={}):                    # load blueprints manager commands, models , views     my_app import core                                                           return app 

core/__init__.py

# . import views 

views.py

from my_app import app, db flask import flask, request  @app.errorhandler(error) def handle_invalid_usage(error):     response = jsonify(data=error.to_dict())     response.status_code = error.status_code     return response 

i based code on tutorial found. works fine long leave __init__.py in core folder empty.

when don't, nameerror: name error not defined in views.py. error comes errors.py.

i have 3 questions:

1) why happen when leave import statement in core/__init__.py.

2)

create_app.py

app.config.from_envvar('env_settings_file') # other app.config commands here  my_app import core  return app 

what happens when from my_app import core runs?

3) when return app, ensure inner __init__.py file contains updated app object?

any explanations appreciated!

trying build , configure app dynamic imports bad news , confusing reasons discovering. better , understandable pattern more typical factory:

def create_app():     app = flask(__name__)     configure_app(app, config)     register_db(app)     add_views(app)     add_manager(app)      return app  if __name__ == '__main__':     app = create_app()     app.run() 

but since you're asking, problem here:

from my_app import app, db flask import flask, request  @app.errorhandler(error) # error not imported def handle_invalid_usage(error):     response = jsonify(data=error.to_dict())     response.status_code = error.status_code     return response 

the error occurs because views.py imported, code compiler comes across error , cannot find reference it.

for second question: from my_app import core causes core.__init.__ run, (presumably) adds views onto app object.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -