Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask structure -- can't import application from __init__.py

Tags:

python

flask

I'm a beginner with python and I've been having a lot of trouble setting up the structure of my applications using __init__.py even after searching through several tutorials.

At the moment, my current directory structure looks like the following

/parent
   /myapp
       __init__.py
       views.py
   /virtualenv

Previously, I had (if it makes any difference)

/parent
   /myapp
   /bin
   /include
   /lib

The contents of __init__.py are below:

 from flask import Flask
 app = Flask(__name__)

and my views.py

 from myapp import app
 @app.route('/')
 def test():
    return 'This is a new test'

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

If myapp is being initialized with the init file, why can't I call it into the views? I get an error stating 'I cannot import app and I have no module named myapp'. If I remove the init file and copy the contents into the top of the views.py file, everything works fine.

like image 661
user2989731 Avatar asked Feb 13 '23 14:02

user2989731


1 Answers

You are using views as the main script. You cannot put a script inside a package; the directory it is in cannot be treated as such. Python adds the parent/myapp directory to the Python path, not the parent path.

Add a separate script at the top level (next to myapp):

from myapp import app

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

and add an import to __init__.py to import your views:

from flask import Flask
app = Flask(__name__)

import views

and remove the if __name__ == '__main__': block from views.py.

like image 125
Martijn Pieters Avatar answered Mar 04 '23 07:03

Martijn Pieters