rasmi
rasmi

Reputation: 391

Flask AttributeError: module 'app' has no attribute 'run'

My Flask project is structured as follows:

my_project
│
├── app
│   ├── __init__.py
│   ├── api
│   ├── static
│   └── templates
├── config.py
└── run.py

app/__init__.py:

from flask import Flask

app = Flask(__name__)

app.config.from_object('config')

run.py

from app import app

app.run(
    host=app.config.get('HOST', '0.0.0.0'),
    port=app.config.get('PORT', 5000)
)

This worked before, but I'm trying to migrate my project from Python 2 to Python 3, and running python run.py no longer works. I get the following error:

Traceback (most recent call last):
  File "/Users/rasmi/Projects/my_project/run.py", line 3, in <module>
    app.run(
AttributeError: module 'app' has no attribute 'run'

If I change the import style in run.py to match the one here:

from .app import app

app.run(
    host=app.config.get('HOST', '0.0.0.0'),
    port=app.config.get('PORT', 5000)
)

I get a different error:

Traceback (most recent call last):
  File "/Users/rasmi/Projects/my_project/run.py", line 1, in <module>
    from .app import app
ModuleNotFoundError: No module named '__main__.app'; '__main__' is not a package

Wrapping my app.run() call in an if __name__ == '__main__': block yields the same results. What's causing this issue?

Upvotes: 8

Views: 35488

Answers (4)

abduljalil
abduljalil

Reputation: 153

can you change your from app import app1 to from app import *?

it worked for me

<code>
├── app
│   ├── __init__.py
│   ├── viewss.py
├── run.py
</code>

I was trying to import app from app/init__.py in run.py

Upvotes: 0

ProgrammingPete
ProgrammingPete

Reputation: 21

I solved this issue by doing this in my runserver.py:

from WebApp import app 
app.app.run(debug=True)

Where the name of the package is Webapp. Noticed how I used app twice. Also, my Flask app is called app.

├── WebApp
│   ├── app.py
│   ├── authentication.py
│   ├── __init__.py
│   ├── models.py
├── runserver.py

Upvotes: 2

Omkar
Omkar

Reputation: 3610

I was facing same issue for below line in my app,

import app.main.constant.constants as Constants

but then I restructure above command to below, and It worked for me.

from app.main.constant import constants as Constants

Upvotes: 1

rasmi
rasmi

Reputation: 391

I fixed this issue by renaming the app directory to something else (e.g. webapp). Using from webapp import app does the trick. This seems to be because package directory names take precedence over module names when importing. Perhaps using __path__ would allow one to get around this.

Upvotes: 15

Related Questions