Bhargav
Bhargav

Reputation: 918

Unable to import module even after adding __init__.py

I am working on a flask application and I have the following directory structure:

flask_app/
|
|-- __init__.py
|-- app.py
|-- views.py
|-- static/
|-- templates/

Example contents of the files are:

app.py:

from flask import Flask
import views

app = Flask(__name__)

if __name__ == '__main__':
    app.run()

views.py:

from app import app

@app.route('/')
def index():
    return "Hello, world!"a

The __init__.py file is empty.

When I run the application, the server starts, but the index page 404's. I understand that I need an __init__.py file for imports to work, so is the views.py file not being imported ?

Upvotes: 1

Views: 1797

Answers (2)

dirn
dirn

Reputation: 20709

You are running into a circular import. When app.py imports views, the processing of app.py pauses while views.py processes. The first thing views.py does is import app from app.py, but app hasn't been defined yet, so app.py is imported. This pauses the processing of views.py and begins processing app.py. Etc.

The Flask documentation provides a solution to this.

app.py

from flask import Flask

flask = Flask(__name__)

import views

if __name__ == '__main__':
    app.run()

views.py

from app import app

@app.route('/')
def index():
    return "Hello, world!"

EDIT: Looking into the flask documentation, adding a run.py to the directory above flask_app and renaming app.py to __init__.py results in the problem being solved.

run.py

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

The directory structure is now as follows:

|run.py
|flask_app/
|
|-- __init__.py
|-- app.py
|-- views.py
|-- static/
|-- templates/

Upvotes: 2

Julia
Julia

Reputation: 397

Code inside if_name==main will be executed in case this file has been run as script, not imported.

Here is how it works for me:

structure:

-> calculator (project folder)

---->calculator (package folder)

-------->_ _init___.py

--------> views.py

--------> createdb.py

---->runserver.py

init.py script

from flask import Flask

app = Flask(__name__)
app.config.update(DEBUG=True)

import createdb
import views

runserver.py script

#!/usr/bin/python

from calculator import app

app.run()

and application is run via command line by calling runserver.py

Upvotes: 0

Related Questions