Everything in Flask hangs off the app object, and the dev server with the debugger is your main feedback loop.
A Flask application is an instance of Flask. You pass it __name__ so Flask knows where to find templates and static files relative to your module. Then you register view functions: ordinary functions that return what the browser should receive, attached to a URL with the @app.route decorator.
Install it into a virtual environment with pip install flask, save the code as app.py and run:
flask --app app run --debugIf the file is called app.py or wsgi.py, plain flask run finds it on its own. The server listens on http://127.0.0.1:5000.
--debug turns on two things: the reloader, which restarts the server when you save a file, and the interactive debugger, which shows a traceback in the browser with a console in each frame when a view raises. Never enable debug mode on a machine reachable from the internet; the debugger console executes arbitrary Python code.
The built-in server is for development only. It is single-process and not hardened; production uses a WSGI server like Gunicorn, covered later.
Returning a string sends it as an HTML page with status 200. You do not need a template for a quick experiment, but be careful: any user input you put into such a string is not escaped, so real pages should use templates.
The test_client() used in the examples sends requests to the app in-process, without a server, which is handy for trying things out.
Example
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello, Flask!</h1>"
@app.route("/about")
def about():
return "A tiny site."
# In a terminal you would run: flask --app app run --debug
# Here we call the app in-process instead:
client = app.test_client()
r = client.get("/")
print(r.status_code, r.text) # 200 <h1>Hello, Flask!</h1>
print(client.get("/missing").status_code) # 404Remember
- app = Flask(__name__) creates the application
- @app.route(path) maps a URL to a view function
- flask --app app run --debug gives auto-reload and the debugger
- The dev server and debugger are never for production
Watch out for
- Leaving --debug on in a deployed app, which exposes a remote Python console.