The Flask documentation on this is pretty good, but here's a simple example.
Let's say you start off with a single-file Flask app like the one PythonAnywhere generates by default. You have a directory called mysite
, containing a file called flask_app.py
, which looks like this:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello from Flask!'
Let's say you've added another view:
@app.route('/goodbye')
def goodbye():
return 'Bye!'
Now, let's say you want to put each view into a separate file. The first step is to create a directory inside your mysite
directory, called flask_app
(note, there's no ".py" extension there).
The next step would be create the two view files inside the new flask_app
directory. Firstly, views1.py
:
from flask_app import app
@app.route('/')
def hello_world():
return 'Hello from Flask!'
Next, views2.py
:
from flask_app import app
@app.route('/goodbye')
def goodbye():
return 'Bye!'
The next step is to create another new file inside the [edit] flask_app
directory called __init__.py
, containing this:
from flask import Flask
app = Flask(__name__)
import flask_app.views1
import flask_app.views2
Finally, you need to remove the original flask_app.py
file, as all of its contents should now be in the other files. (Just to be safe, perhaps move it somewhere else in case you forgot to move all of the contents.)
Once you've done that, reload the web app, and it should work fine.
[edit: originally I said that the __init__.py
file should be in the mysite
directory, which was wrong.]