Forums

Struggling with Basic Flask App Structure - Simple Solution?

So I have been able to successfully create a basic site based on Flask with a single module (mysite.py) and some template files in a template directory. As my code continues to get more complicated, I am now trying to split things out so that the application module is easier to read. After running into issues, I went back to the basics and did the following:

  1. Created a new site - Manual Configuration
  2. Setup virtualenv
  3. Installed flask

I then setup my files as follows:

├── mysite

│ ├── app

│ │ └── views.py

├── flask_app.py

flask_app.py

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

views.py

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

wsgi file

activate_this = '/home/tkuehn/.virtualenvs/superapp/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))

import sys

project_home = u'/home/tkuehn/mysite'
if project_home not in sys.path:
    sys.path = [project_home] + sys.path

from flask_app import app as application

After all this, my site produces the error: "Unhandled Exception" and generates the following in the error log: ImportError: No module named app.views

I feel like I am making a very basic error. Can anyone point me in the right direction? Thanks!

Is there a __init__.py in the app folder?

Thanks for the response harry. That's something I forgot to mention - If I add the _ init _.py file in the app folder, I then end up iwth a 502 Bad Gateway error.

Well it's certainly not going to work without a __init__.py, but there definitely is another problem here. Investigating...

Aha. Figured it out. It was this line:

app.run(debug=True)

Don't do this. It tells flask to try and run its own WSGI server. We do that for you using uWSGI. If you try and run your own it just breaks.

Thanks harry for taking the time to help me out with this. Very much appreciated!

Anytime!

So did this need the init.py file? If so what's in it?

The __init__.py is just a marker that tells Python that the directory it is in is a package directory so you can import things from it. It can just be an empty file. Here is some more detail

Is there any particular reason to use this file structure? I'm starting my first Flask project and I was just going to put all of my code in the flask_app.py file in the root of my site.

No. To start out with just have everything in flask_app.py

But when you start to have too much code in that single file and want to break it out, then check out this.