Reputation: 16860
I can't get it to work to use one module that creates the Flask application object and runs it, and one module that implements the views (routes and errorhandlers). The modules are not contained in a Python package.
app.py
from flask import Flask
app = Flask('graphlog')
import config
import views
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
views.py
from app import app
@app.route('/')
def index():
return 'Hello!'
config.py
host = 'localhost'
port = 8080
debug = True
I always get Flask's default "404 Not Found" page. If I move the contents of view.py
to app.py
however, it works. What's the problem here?
Upvotes: 4
Views: 3054
Reputation: 1121266
You have four modules here:
__main__
, the main script, the file you gave to the Python command to run.config
, loaded from the config.py
file.views
, loaded from the views.py
file.app
, loaded from app.py
when you use import app
.Note that the latter is separate from the first! The initial script is not loaded as app
and Python sees it as different. You have two Flask
objects, one referenced as __main__.app
, the other as app.app
.
Create a separate file to be the main entry point for your script; say run.py
:
from app import app
import config
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
and remove the import config
line from app.py
, as well as the last two lines.
Alternatively (but much uglier), use from __main__ import app
in views.py
.
Upvotes: 6