user2268507
user2268507

Reputation:

Importing Views

My app layout

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

Inner __init__.py

from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)           # The WSGI compliant web application object
db = SQLAlchemy(app)            # Setup Flask-SQLAlchemy
manager = Manager(app)          # Setup Flask-Script

from my_app.startup.create_app import create_app
create_app()

create_app.py

from native_linguist_server import app, db

@app.before_first_request
def initialize_app_on_first_request():
    """ Create users and roles tables on first HTTP request """
    from .create_users import create_users
    create_users()

def create_app(extra_config_settings={}):   

    app.config.from_envvar('ENV_SETTINGS_FILE')          

    # Load all blueprints with their manager commands, models and views
    from my_app import core                                                     

    return app

When I run my app like this and try to load a view in my browser, I get a 404 error.

However if I change:

from my_app import core    

to

from my_app.core import views

it works fine.

Could someone please explain to me the difference between these two calls? I would have thought from my_app import core would also import views.py and hence there wouldn't be an issue.

Thank you.

Upvotes: 0

Views: 331

Answers (1)

dirn
dirn

Reputation: 20739

from my_app import core

will load and execute my_app/core/__init__.py (if it exists). You will then have access to any identifiers defined inside or imported into __init__.py.

from my_app.core import views

will load and execute my_app/core/views.py. You'll then have access to any identifiers defined inside or imported into views.py.

To get the behavior you're expecting, you'll need to import views inside __init__.py:

from . import views

Upvotes: 1

Related Questions