2017-12-05T17:15:48Z

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

@app.route('/')
@app.route('/index')
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:

microblog/
  venv/
  app/
    __init__.py
    routes.py
  microblog.py

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 http://127.0.0.1:5000/ (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 127.0.0.1, 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:

http://localhost:5000/

Alternatively you can use this other URL:

http://localhost:5000/index

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

FLASK_APP=microblog.py

544 comments

  • #151 Mohammed said 2018-06-04T13:57:11Z

    dear miguel,

    thank you for the interesting tutorials.. i'm facing an error blocks me from following up this tutorial whenever i tried to run the microblog.py with flask run:

    lask.cli.NoAppException NoAppException: While importing "app.microblog", an ImportError was raised:

    Traceback (most recent call last): File "c:\python27\lib\site-packages\flask\cli.py", line 235, in locate_app import(module_name) File "C:\Users\ACER\FlaskTEST\venv\app\MicroBlog\app__init__.py", line 5, in from app import routes File "C:\Users\ACER\FlaskTEST\venv\app\MicroBlog\app\app.py", line 4, in from app import views ImportError: cannot import name views

  • #152 Miguel Grinberg said 2018-06-04T17:31:31Z

    @Akshay: my guess is that you have your FLASK_APP environment variable incorrectly set. From the error message it appears you have a set of extra quotes in there, note that the error says ""microblog.py"" and not "microblog.py".

  • #153 Miguel Grinberg said 2018-06-04T17:33:40Z

    @Mohammed: compare your project structure against mine on GitHub. I think you have microblog.py in the wrong place.

  • #154 A.C. Miller said 2018-06-13T02:21:20Z

    Like the tutorial so far but I am having an issue. The hello world app wont run. I set the FLASK_APP environment variable and then did flask run and I get Error: Could not import "microblog".

  • #155 Miguel Grinberg said 2018-06-13T03:31:28Z

    @AC: where did you put the file microblog.py? It should be in the top-level directory, so it should be at the same level as the app directory, not inside it.

  • #156 desheng said 2018-06-13T20:01:11Z

    Thanks for the tutorial. Created everything same as what you did, while when flask run got this error:

    Error: While importing "microblog", an ImportError was raised:

    Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/flask/cli.py", line 235, in locate_app import(module_name) File "/mnt/bfd/tmp/try_flask/microblog/microblog.py", line 1, in from app import app ImportError: cannot import name 'app'

  • #157 Miguel Grinberg said 2018-06-13T23:45:48Z

    @desheng: I can't tell you exactly what's different, but you don't have the structure of the project in the correct way. I recommend that you follow the GitHub link at the top of the article and compare your files against my version.

  • #158 SummittDweller said 2018-06-20T20:25:38Z

    Thanks for the tutorial! I've just gotten started with it and wonder if I am headed down a viable path? I'm mostly play a PHP dev-ops role but do a lot of my utility scripting in Python. I have a desktop Python script that uses Tk for a GUI and I'd like to now Dockerize that app, but Tk makes that tricky. So I looked a Python features and see that you have all the parts I need (forms, templates, CSS, and Docker...Chapters 1-3, 11 and 19 look relevant, maybe Chapter 7), and much more in Microblog, along with a great write-up!

    Thus far I've successfully spun up the whole project in Docker, and less-successfully tried removing some of the parts I did not need. I've also worked through Chapters 1-3 successfully, but am having no luck spinning up that creation in Docker.

    Any suggestion which process might be easiest and most fruitful? Or am I destined to fail on both fronts? Would you recommend an alternative approach? Maybe something other than Flask for this task? Thanks.

  • #159 Miguel Grinberg said 2018-06-21T06:00:15Z

    @SummittDweller: I don't quite follow what you are trying to do. This tutorial is for web development, not GUI. You should be able to dockerize a GUI app on Unix, as long as you point the container at a valid X server where the GUI can be displayed. Not sure if this is possible for a Windows app, my guess is that it isn't.

  • #160 Kari said 2018-07-09T03:48:55Z

    Hi Miguel, What do you use for creating/editing your python files? Do you use a code editor or an IDE, or something else?

  • #161 Miguel Grinberg said 2018-07-09T16:37:56Z

    @Kari: Most of the time I use vim, which is a text editor. I also like Visual Studio Code and PyCharm a lot.

  • #162 Ityav Luke said 2018-07-11T11:36:14Z

    Sir, I have got an error; after following the blog step by step. C:\Users\Luke>cd gitsource

    C:\Users\Luke\gitsource>cd microblog

    C:\Users\Luke\gitsource\microblog>venv\Scripts\activate

    (venv) C:\Users\Luke\gitsource\microblog>set FLASK_APP=microblog.py (venv) C:\Users\Luke\gitsource\microblog>flask run * Serving Flask app "microblog.py" * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: off Usage: flask run [OPTIONS]

    Error: Could not import "microblog".

    I am using Windows 7 64bit Python 3.6.5

    My app directory structure is: C:\Users\Luke\gitsource\microblog\venv\app where i have the following files:init.py , microblog.py , and routes.py All contains the exact code written. Thanks

  • #163 Miguel Grinberg said 2018-07-13T17:53:22Z

    @Ityav: don't put your application files inside the virtual environment. The files should go in the microblog directory. The microblog.py and the venv directory should be at the same level.

  • #164 Paul said 2018-07-16T17:45:00Z

    Hi Miguel,

    I think I've followed your instructions carefully, and checked and rechecked the code and placement of the files (and the venv). But I'm getting this error on startup and it's driving me crazy...

    File "/home/pi/work/flask_tuts/microblog/app/init.py", line 7, in from app import routes File "/home/pi/work/flask_tuts/microblog/app/routes.py", line 6, in @app.index('/index') AttributeError: 'Flask' object has no attribute 'index'

    I've searched through the comments here and searched online for answers but am unable to figure where I have gone wrong.

    Can you offer some advice?

  • #165 Miguel Grinberg said 2018-07-16T17:50:48Z

    @Paul: the decorator is @app.route, not @app.index.

  • #166 Sam Bhandu said 2018-07-18T07:43:02Z

    Miguel, Thank you so much for this awesome tutorial and the book 'The New And Improved Flask Mega-Tutorial'. I have been learning a lot from both. I would like to ask you if you have any suggestions on how to implement role-based access control to the blog page. Any recommendation would help a lot.

  • #167 Miguel Grinberg said 2018-07-18T18:41:22Z

    @Sam: The basic implementation requires that you store the role for each user in the user table. After you have that, you can check that the role is adequate at the beginning of each route. If you want to make the role access easier to use, you can write a custom decorator similar to login_required that checks for roles.

  • #168 Yoshi said 2018-07-30T14:20:44Z

    This is amazing! Thanks for sharing this tutorial, the best ever!

  • #169 Chris said 2018-07-31T03:14:31Z

    As a university student that is diving into python and web development I can't thank you enough for your time and effort to make free resources like this available. Far more comprehensive than the official tutorial, thank you!

  • #170 ELIYAHU STERNBERG said 2018-08-03T15:23:08Z

    What does this mean WARNING: Do not use the development server in a production environment? I am getting that every time I try to run the program I created a different microblog and didn't get that message now I wanted to start from scratch again.

  • #171 Miguel Grinberg said 2018-08-04T07:52:54Z

    @ELIYAHU: it's telling you that the server that you are using is not appropriate for production use. Later in this tutorial you are going to learn how to run your Flask app in production.

  • #172 Zion Oyemade said 2018-08-04T22:55:34Z

    Hi Miguel, Great Book, From the very start, I enjoyed following it. I have a question please. I'd like to keep the server running instead of having to shut down and restart whenever an edit is made. Now I got to know the Debug has o be set t True. Please could you point out how exactly to do that, I have tried every method online to set Debug to True, It just wont work. Al I want to is to be able to see refreshes on my work without having to restart the server.

  • #173 Miguel Grinberg said 2018-08-05T07:55:37Z

    @Zion: this is covered in chapter 7 of this tutorial, but if you want the short version, set FLASK_DEBUG=1 before running "flask run".

  • #174 Zion Oyemade said 2018-08-05T13:13:44Z

    Thanks for the response Miguel. guess what, I did set the Debug option however its still not working. I have attached a screenshot here https://paste.pics/3ISO3

  • #175 Miguel Grinberg said 2018-08-07T21:12:00Z

    @Zion: you are using PowerShell. The instructions in this tutorial are for command prompt.

Leave a Comment