The Flask Mega-Tutorial Part I: Hello, World!

Welcome! You are about to start on a journey to learn how to create web applications with Python and the Flask framework. In this first chapter, you are going to learn how to set up a Flask project. By the end of this chapter you are going to have a simple Flask web application running on your computer!

For your reference, below is a list of the articles in this series.

All the code examples presented in this book are hosted on a GitHub repository. Downloading the code from GitHub can save you a lot of typing, but I strongly recommend that you type the code yourself, at least for the first few chapters. Once you become more familiar with Flask and the example application you can access the code directly from GitHub if the typing becomes too tedious.

At the beginning of each chapter, I'm going to give you three GitHub links that can be useful while you work through the chapter. The Browse link will open the GitHub repository for Microblog at the place where the changes for the chapter you are reading were added, without including any changes introduced in future chapters. The Zip link is a download link for a zip file including the entire application up to and including the changes in the chapter. The Diff link will open a graphical view of all the changes that were made in the chapter you are about to read.

The GitHub links for this chapter are: Browse, Zip, Diff.

Installing Python

If you don't have Python installed on your computer, go ahead and install it now. If your operating system does not provide you with a Python package, you can download an installer from the Python official website. If you are using Microsoft Windows along with WSL or Cygwin, note that you will not be using the Windows native version of Python, but a Unix-friendly version that you need to obtain from Ubuntu (if you are using WSL) or from Cygwin.

To make sure your Python installation is functional, you can open a terminal window and type python3, or if that does not work, just python. Here is what you should expect to see:

$ python3
Python 3.9.6 (default, Jul 10 2021, 16:13:29)
[Clang 12.0.0 (clang-1200.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> _

The Python interpreter is now waiting at an interactive prompt, where you can enter Python statements. In future chapters you will learn what kinds of things this interactive prompt is useful for. But for now, you have confirmed that Python is installed on your system. To exit the interactive prompt, you can type exit() and press Enter. On the Linux and Mac OS X versions of Python you can also exit the interpreter by pressing Ctrl-D. On Windows, the exit shortcut is Ctrl-Z followed by Enter.

Installing Flask

The next step is to install Flask, but before I go into that I want to tell you about the best practices associated with installing Python packages.

In Python, packages such as Flask are available in a public repository, from where anybody can download them and install them. The official Python package repository is called PyPI, which stands for Python Package Index (some people also refer to this repository as the "cheese shop"). Installing a package from PyPI is very simple, because Python comes with a tool called pip that does this work.

To install a package on your machine, you use pip as follows:

$ pip install <package-name>

Interestingly, this method of installing packages will not work in most cases. If your Python interpreter was installed globally for all the users of your computer, chances are your regular user account is not going to have permission to make modifications to it, so the only way to make the command above work is to run it from an administrator account. But even without that complication, consider what happens when you install a package as above. The pip tool is going to download the package from PyPI, and then add it to your Python installation. From that point on, every Python script that you have on your system will have access to this package. Imagine a situation where you have completed a web application using version 1.1 of Flask, which was the most current version of Flask when you started, but now has been superseded by version 2.0. You now want to start a second application, for which you'd like to use the 2.0 version, but if you replace the 1.1 version that you have installed you risk breaking your older application. Do you see the problem? It would be ideal if it was possible to have Flask 1.1 installed and accessible to your old application, while also install Flask 2.0 for your new one.

To address the issue of maintaining different versions of packages for different applications, Python uses the concept of virtual environments. A virtual environment is a complete copy of the Python interpreter. When you install packages in a virtual environment, the system-wide Python interpreter is not affected, only the copy is. So the solution to have complete freedom to install any versions of your packages for each application is to use a different virtual environment for each application. Virtual environments have the added benefit that they are owned by the user who creates them, so they do not require an administrator account.

Let's start by creating a directory where the project will live. I'm going to call this directory microblog, since that is the name of the application:

$ mkdir microblog
$ cd microblog

Support for virtual environments is included in all recent versions of Python, so all you need to do to create one is this:

$ python3 -m venv venv

With this command, I'm asking Python to run the venv package, which creates a virtual environment named venv. The first venv in the command is the name of the Python virtual environment package, and the second is the virtual environment name that I'm going to use for this particular environment. If you find this confusing, you can replace the second venv with a different name that you want to assign to your virtual environment. In general I create my virtual environments with the name venv in the project directory, so whenever I cd into a project I find its corresponding virtual environment.

Note that in some operating systems you may need to use python instead of python3 in the command above. Some installations use python for Python 2.x releases and python3 for the 3.x releases, while others map python to the 3.x releases.

After the command completes, you are going to have a directory named venv where the virtual environment files are stored.

Now you have to tell the system that you want to use this virtual environment, and you do that by activating it. To activate your brand new virtual environment you use the following command:

$ source venv/bin/activate
(venv) $ _

If you are using a Microsoft Windows command prompt window, the activation command is slightly different:

$ venv\Scripts\activate
(venv) $ _

When you activate a virtual environment, the configuration of your terminal session is modified so that the Python interpreter stored inside it is the one that is invoked when you type python. Also, the terminal prompt is modified to include the name of the activated virtual environment. The changes made to your terminal session are all temporary and private to that session, so they will not persist when you close the terminal window. If you work with multiple terminal windows open at the same time, it is perfectly fine to have different virtual environments activated on each one.

Now that you have a virtual environment created and activated, you can finally install Flask in it:

(venv) $ pip install flask

If you want to confirm that your virtual environment now has Flask installed, you can start the Python interpreter and import Flask into it:

>>> import flask
>>> _

If this statement does not give you any errors you can congratulate yourself, as Flask is installed and ready to be used.

Note that the above installation commands does not specify which version of Flask you want to install. The default when no version is specified is to install the latest version available in the package repository. This tutorial can be followed with Flask versions 1 and 2. The above command will install the latest 2.x version. If for any reason you prefer to follow this tutorial on a 1.x release of Flask, you can use the following command to install the latest 1.x version:

(venv) % pip install "flask<2"

A "Hello, World" Flask Application

If you go to the Flask website, you are welcomed with a very simple example application that has just five lines of code. Instead of repeating that trivial example, I'm going to show you a slightly more elaborate one that will give you a good base structure for writing larger applications.

The application will exist in a package. In Python, a sub-directory that includes a __init__.py file is considered a package, and can be imported. When you import a package, the __init__.py executes and defines what symbols the package exposes to the outside world.

Let's create a package called app, that will host the application. Make sure you are in the microblog directory and then run the following command:

(venv) $ mkdir app

The __init__.py for the app package is going to contain the following code:

app/__init__.py: Flask application instance

from flask import Flask

app = Flask(__name__)

from app import routes

The script above simply creates the application object as an instance of class Flask imported from the flask package. The __name__ variable passed to the Flask class is a Python predefined variable, which is set to the name of the module in which it is used. Flask uses the location of the module passed here as a starting point when it needs to load associated resources such as template files, which I will cover in Chapter 2. For all practical purposes, passing __name__ is almost always going to configure Flask in the correct way. The application then imports the routes module, which doesn't exist yet.

One aspect that may seem confusing at first is that there are two entities named app. The app package is defined by the app directory and the __init__.py script, and is referenced in the from app import routes statement. The app variable is defined as an instance of class Flask in the __init__.py script, which makes it a member of the app package.

Another peculiarity is that the routes module is imported at the bottom and not at the top of the script as it is always done. The bottom import is a workaround to circular imports, a common problem with Flask applications. You are going to see that the routes module needs to import the app variable defined in this script, so putting one of the reciprocal imports at the bottom avoids the error that results from the mutual references between these two files.

So what goes in the routes module? The routes are the different URLs that the application implements. In Flask, handlers for the application routes are written as Python functions, called view functions. View functions are mapped to one or more route URLs so that Flask knows what logic to execute when a client requests a given URL.

Here is the first view function for this application, which you need to write in a new module named app/routes.py:

app/routes.py: Home page route

from app import app

def index():
    return "Hello, World!"

This view function is actually pretty simple, it just returns a greeting as a string. The two strange @app.route lines above the function are decorators, a unique feature of the Python language. A decorator modifies the function that follows it. A common pattern with decorators is to use them to register functions as callbacks for certain events. In this case, the @app.route decorator creates an association between the URL given as an argument and the function. In this example there are two decorators, which associate the URLs / and /index to this function. This means that when a web browser requests either of these two URLs, Flask is going to invoke this function and pass the return value of it back to the browser as a response. If this does not make complete sense yet, it will in a little bit when you run this application.

To complete the application, you need to have a Python script at the top-level that defines the Flask application instance. Let's call this script microblog.py, and define it as a single line that imports the application instance:

microblog.py: Main application module

from app import app

Remember the two app entities? Here you can see both together in the same sentence. The Flask application instance is called app and is a member of the app package. The from app import app statement imports the app variable that is a member of the app package. If you find this confusing, you can rename either the package or the variable to something else.

Just to make sure that you are doing everything correctly, below you can see a diagram of the project structure so far:


Believe it or not, this first version of the application is now complete! Before running it, though, Flask needs to be told how to import it, by setting the FLASK_APP environment variable:

(venv) $ export FLASK_APP=microblog.py

If you are using the Microsoft Windows command prompt, use set instead of export in the command above.

Are you ready to be blown away? You can run your first web application, with the following command:

(venv) $ flask run
 * Serving Flask app 'microblog.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on (Press CTRL+C to quit)

After the server initializes it will wait for client connections. The output from flask run indicates that the server is running on IP address, which is always the address of your own computer. This address is so common that is also has a simpler name that you may have seen before: localhost. Network servers listen for connections on a specific port number. Applications deployed on production web servers typically listen on port 443, or sometimes 80 if they do not implement encryption, but access to these ports requireis administration rights. Since this application is running in a development environment, Flask uses the freely available port 5000. Now open up your web browser and enter the following URL in the address field:


Alternatively you can use this other URL:


Do you see the application route mappings in action? The first URL maps to /, while the second maps to /index. Both routes are associated with the only view function in the application, so they produce the same output, which is the string that the function returns. If you enter any other URL you will get an error, since only these two URLs are recognized by the application.

Hello, World!

When you are done playing with the server you can just press Ctrl-C to stop it.

Congratulations, you have completed the first big step to become a web developer!

Before I end this chapter, I will do one more thing. Since environment variables aren't remembered across terminal sessions, you may find tedious to always have to set the FLASK_APP environment variable when you open a new terminal window. Starting with version 1.0, Flask allows you to register environment variables that you want to be automatically imported when you run the flask command. To use this option you have to install the python-dotenv package:

(venv) $ pip install python-dotenv

Then you can just write the environment variable name and value in a file named .flaskenv located in the top-level directory of the project:

.flaskenv: Environment variables for flask command



  • #476 pasqpasq said 2021-01-04T12:48:17Z

    Hi Miguel, I'm deciding which content to buy. How is your course (https://courses.miguelgrinberg.com/p/flask-mega-tutorial) different from your book (https://www.amazon.co.uk/Flask-Web-Development-Miquel-Grinberg/dp/1491991739/)? Thanks

  • #477 Miguel Grinberg said 2021-01-04T23:23:28Z

    @pasqpasq: The Mega-Tutorial course covers a wider range of topics. The O'Reilly book focuses more on Flask and a small set of core extensions.

  • #478 Kingsley said 2021-01-09T09:52:41Z

    Thanks for the tutorial. I keep getting this error when I flask run that "This version of flask.exe is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher". What do I do? I use Window 10.

  • #479 Miguel Grinberg said 2021-01-09T18:30:29Z

    @Kingsley: this is likely a mismatch between the 32-bit and 64-bit versions of Windows. You must use a Python interpreter that is compatible with your Windows 10 version, which can be for 32-bit or 64-bit.

  • #480 Ahmed said 2021-01-17T02:20:01Z

    What a magic tutorial! this is the first time I read a tutorial and actually enjoy it. you're explaining everything and giving all the information along the way to make it completely clear in a good and easy language. Thank you so much for such effort <3

  • #481 Phil Goddard said 2021-01-23T22:03:20Z

    Miguel I've been working working through your tutorial which is excellent. I have hit a couple roadblocks and need support. On the email server chapter - I'm getting this traceback: lask Mega/microblog/app/models.py", line 67, in get_reset_password_token app.config['SECRET_KEY'], algorithm='HS256').decode('utf-8') - AttributeError: 'str' object has no attribute 'decode'

    Any thoughts would be very welcome :)

  • #482 Miguel Grinberg said 2021-01-23T22:50:09Z

    @Phil: for recent versions of the pyjwt package, that decode('utf-8') call that you have in your code should not be used.

  • #483 Mutaz Alsayegh said 2021-01-25T07:40:38Z

    Miguel, I'm using a VM on Google Cloud. I get Error 500 (Server Error) when I click on http://localhost:5000/ after compiling run flask. Reason for using VM is that I like to use Linux environment...

    How can I see what I am developing on VM? Would appreciate your help with this if possible .

  • #484 Miguel Grinberg said 2021-01-25T15:26:34Z

    @Mutaz: I do not undestand what you are asking me. If you have a VM, can't you just ssh into it and work directly on it? This would be no different than working on a Linux machine.

  • #485 Mutaz Alsayegh said 2021-01-25T16:17:25Z

    I do ssh into it and work directly on it. My challenge is when I compile code (execute flask run) and click on http://localhost:5000/ I get Error 500 (server error) and not able to see "Hello, World!". Hope that makes sense.

  • #486 Miguel Grinberg said 2021-01-25T17:47:34Z

    @Mutaz: Look at the console where you are running the application for an error. The 500 error means that something crashed in your Python code. The output in the terminal will have a stack trace.

  • #487 KP said 2021-02-05T04:13:35Z


    From the Flask documentation:

    app = Flask(name.split('.')[0]) Why is that? The application will work even with name, thanks to how resources are looked up. However it will make debugging more painful. Certain extensions can make assumptions based on the import name of your application.

    You are just using name - should one rather follow the Flask docs here?


  • #488 Miguel Grinberg said 2021-02-05T10:34:50Z

    @KP: It doesn't really matter much in most cases. I have a blog post that explains what this argument does, if you are interested: https://blog.miguelgrinberg.com/post/why-do-we-pass-name-to-the-flask-class.

  • #489 kumar said 2021-02-06T05:17:45Z

    miguel how can we access individual fields from database? like user.name and user.email?

  • #490 Miguel Grinberg said 2021-02-06T17:50:19Z

    @kumar: You are getting ahead of yourself. Chapter 4 covers database use.

  • #491 Green Mark said 2021-02-20T06:28:07Z

    Thanks for all.

  • #492 Winson said 2021-03-05T08:47:26Z

    Awesome tutorial

  • #493 Tarcisio said 2021-03-07T00:59:09Z

    I'm new to Python and after small searching on the internet o land out on this blog. Thanks for this huge and very good tutorial!

  • #494 Ray said 2021-03-09T17:17:10Z

    Is the full application production ready i.e whatever we have developed in this mega tutorial if we make it public will it work or it will break if there's significant traffic?

  • #495 Miguel Grinberg said 2021-03-09T17:51:27Z

    @Ray: The application is robust and supports horizontal scalability. You will need to adjust the scaling of your deployment to handle the amount of traffic that you need, though.

  • #496 Pedro said 2021-03-12T18:12:38Z

    I've been trying to study the system of logging with flask and I feel very happy when i found that material. All others, since video and blogs, aren't so complete and well taught like yours(my opinion). The most astonishing thing that I've seen in this article is that I learned a couple things that wasn't my main goal, like the structure of folders in flask (My personal projects were kind of a mess in this topic xD) and the final tip of the package python-dotenv really changed my life(and patience lol). Congratulations for the work and thanks !

    By the way, 2021 and it still helping a lot of people =]

  • #497 sut said 2021-03-17T12:24:17Z

    not often for me that i found the author can explain thing in logical way at this level. You seem to catch all the obscure things I form in my head like magic. Any book/course you make in future is an instant buy for me (i even rarely write review also!).

  • #498 Martin Maes said 2021-03-27T16:13:19Z

    Hello Miguel, Thank you for sharing this tutorial with the world. I just got started with it and had problems with my "Hello world" script on my AWS Centos machine. I couldn't connect to it (connection refused messages). I tried a lot but didn't find a solution until I discovered the flask application should be run with the hostname to accept request from others then so, with "flask run -h -p 5000" it's working. Just wanted to share this and maybe help others with the same issue. Kind regards, Martin

  • #499 Miguel Grinberg said 2021-03-27T23:27:42Z

    @Martin: the tutorial is designed to be followed on your local machine, not on a cloud server.

  • #500 app-vs-fapp said 2021-03-28T18:13:28Z

    Why are we adding confusion by adding duplicate names (app - package / variable, venv - module / env-name)?

    Use "app" for the package. Use "fapp" for the flask app variable.

    cat microblog.py 
    from app import fapp
    cat app/__init__.py 
    from flask import Flask
    fapp = Flask(__name__)
    from app import routes
    cat app/routes.py 
    from app import fapp
    def index():
        return "Hello, World!"

Leave a Comment