By Flask Team

 

A minimal Flask application looks something like this:

 

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

 

So what did that code do?

 

  1. First we imported the Flask class. An instance of this class will be our WSGI application. 
  2. Next we create an instance of this class. The first argument is the name of the application’s module or package. __name__ is a convenient shortcut for this that is appropriate for most cases. This is needed so that Flask knows where to look for resources such as templates and static files. 
  3. We then use the route() decorator to tell Flask what URL should trigger our function. 
  4. The function returns the message we want to display in the user’s browser. The default content type is HTML, so HTML in the string will be rendered by the browser.

 

Save it as hello.py or something similar. Make sure to not call your application flask.py because this would conflict with Flask itself. 

 

To run the application, use the flask command or python -m flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP environment variable:

 

# Bash

$ export FLASK_APP=hello
$ flask run
 * Running on http://127.0.0.1:5000/
 
 # Powershell
 > $env:FLASK_APP = "hello"
> flask run
 * Running on http://127.0.0.1:5000/

 

Application Discovery Behavior

 

As a shortcut, if the file is named app.py or wsgi.py, you don’t have to set the FLASK_APP environment variable. See Command Line Interface for more details.

 

This launches a very simple builtin server, which is good enough for testing but probably not what you want to use in production. For deployment options see Deploying to Production. 

 

Now head over to http://127.0.0.1:5000/, and you should see your hello world greeting. 

 

If another program is already using port 5000, you’ll see OSError: [Errno 98] or OSError: [WinError 10013] when the server tries to start. See Address already in use for how to handle that.