Forums

Importing __init__.py in my wsgi does not work

Hi,

I built a Flask app on my laptop locally and wanted to deploy it at PythonAnywhere. I'm getting this error.

2020-08-27 19:55:50,690: Error running WSGI application
2020-08-27 19:55:50,690: ImportError: cannot import name 'app' from 'mysite' (/home/davelojk/mysite/__init__.py)
2020-08-27 19:55:50,690:   File "/var/www/davelojk_pythonanywhere_com_wsgi.py", line 16, in <module>
2020-08-27 19:55:50,690:     from mysite import app as application  # noqa
2020-08-27 19:55:50,690: ***************************************************
2020-08-27 19:55:50,690: If you're seeing an import error and don't know why,
2020-08-27 19:55:50,690: we have a dedicated help page to help you debug: 
2020-08-27 19:55:50,691: https://help.pythonanywhere.com/pages/DebuggingImportError/
2020-08-27 19:55:50,691: ***************************************************

I did try to go to https://help.pythonanywhere.com/pages/DebuggingImportError/ but no luck figuring what the error could be.

__init_.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager

db = SQLAlchemy()

def create_app():
    app = Flask(__name__)

    app.config['SECRET_KEY'] = 'secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'

    db.init_app(app)

    from .dash_app import dashboard
    dash = dashboard.init_dash_app()

    dash.init_app(app = app)

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    from .models import user

    @login_manager.user_loader
    def load_user(user_id):
        return user.query.get(int(user_id))

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    dashboard.protect_views(dash)

    return app

wsgi file:

import sys

# add your project directory to the sys.path
project_home = '/home/davelojk'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

# import flask app but need to call it "application" for WSGI to work
from mysite import app as application  # noqa

Is there anything I am missing?

Thank you very much for your help!

David

Nothing is calling create_app in your init file.

The problem was actually in the wsgi file. If someone encounters the same problem when using a factory function, the solution is to use (in the wsgi file):

from yourapplication import create_app
application = create_app()

As it is in the flask docs here - https://flask.palletsprojects.com/en/1.1.x/deploying/mod_wsgi/

Thanks!