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. The video above will give you an overview of the contents of this tutorial. 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.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

All the code examples presented in this tutorial 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.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
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 (in Python 2.7 pip does not come bundled with Python and needs to be installed separately).

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 0.11 of Flask, which was the most current version of Flask when you started, but now has been superseeded by version 0.12. You now want to start a second application, for which you'd like to use the 0.12 version, but if you replace the 0.11 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 install Flask 0.11 to be used by your old application, and also install Flask 0.12 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

If you are using a Python 3 version, virtual environment support is included in it, 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.

If you are using any version of Python older than 3.4 (and that includes the 2.7 release), virtual environments are not supported natively. For those versions of Python, you need to download and install a third-party tool called virtualenv before you can create virtual environments. Once virtualenv is installed, you can create a virtual environment with the following command:

$ virtualenv venv

Regardless of the method you used to create it, you should have your virtual environment created. Now you have to tell the system that you want to use it, 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.

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 your first view function, which you need to write in the 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 Microsoft Windows, 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"
 * 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 require 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 want to mention 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 .flaskenv file in the top-level directory of the project:

.flaskenv: Environment variables for flask command

FLASK_APP=microblog.py

Doing this is optional. If you prefer to set the environment variable manually, that is perfectly fine, as long as you always remember to do it.

461 comments

  • #301 Shaistha said 2019-06-12T12:02:42Z

    I'm trying to solve this for more than 6 hours, but couldn't,,

    flask.cli.NoAppException flask.cli.NoAppException: Could not import "app".

    Traceback (most recent call last) File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 330, in call rv = self._load_unlocked() File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 317, in _load_unlocked self._app = rv = self.loader() File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 372, in load_app app = locate_app(self, import_name, name) File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 246, in locate_app 'Could not import "{name}".'.format(name=module_name) flask.cli.NoAppException: Could not import "app".

  • #302 Miguel Grinberg said 2019-06-12T15:21:14Z

    @Shaistha: what's the value of your FLASK_APP environment variable?

  • #303 Daniel Magal said 2019-06-17T21:29:26Z

    Hi Miguel, I'm in the deployment phase. Since Apache is the more common WebServer (in general, not sure if this is the case for python applications) and I own, can you please share the steps to deploy the application on an Apache WebServer?

    I found a post from you from 2013, here: https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xvii-deployment-on-linux-even-on-the-raspberry-pi-legacy

    There are many sources for how to do it, but it looks like everyone has their own approach, Can you direct to the right source to learn from?

    -Daniel

  • #304 Miguel Grinberg said 2019-06-18T10:54:14Z

    @Daniel: Sorry, I do not work with Apache. My recommendations for 2019 are the deployment chapters I included in this tutorial.

  • #305 ravi said 2019-06-18T21:48:38Z

    Do you also have a tutorial geared towards windows users as it gets confusing to run the commands in the tutorial and run into different errors.

  • #306 Miguel Grinberg said 2019-06-19T08:34:36Z

    @ravi: You can see in this article that the differences for Windows users are not that many, and they are noted where appropriate. If you are getting a specific error that you want me to help you with then show me what you are getting.

  • #307 shahriar said 2019-06-22T19:56:37Z

    hello, greetings I'm using CMD, and when I write : "flask run" it says Error: could not import "microblog" whats wrong?

  • #308 Miguel Grinberg said 2019-06-22T22:34:44Z

    @shahriar: it could be a couple of things. Either you don't have a microblog.py in the current directory, or maybe you have it, but it has some errors so it fails to import. Compare your code against mine to find out what the problem is.

  • #309 Rachel said 2019-06-28T03:19:50Z

    Hello Miguel,

    Thank you for this wonderful tutorial. I am trying to follow the steps here to create my first flask application. I do have a question though. When I tried to run route.py, it always give me an error message 'AssertionError: View function mapping is overwriting an existing endpoint function: index.' I looked through a couple of posts on Stackflow and none of them addressed my problem here. Someone suggested that 'This error is because you are cyclic import app (you imported app in routes.py and imported routes.py in app)'. But since you explicitly stated in your post that by importing routes at bottom we avoids issues with circular imports. I was wondering if you could give me more insights into this. Thank you so much for your attention and help!

  • #310 Miguel Grinberg said 2019-06-28T10:26:58Z

    @Rachel: this error means that you have two (or more) view functions named index. The name of each view function needs to be unique.

  • #311 Rachel said 2019-07-01T22:14:38Z

    That's what I thought too. But I double checked and compared my code with yours, and surprisingly they were the same. My application was able to run smoothly even with this error but if I tried to run this code in python console it will always give me such an error. Does this matter?

  • #312 Miguel Grinberg said 2019-07-01T22:20:25Z

    @Rachel: Your code can't be the same as mine, I think you must be missing some difference there. Did you compare all the Python files?

  • #313 jeex said 2019-07-02T20:08:31Z

    are you going to rewrite this series for flask 1.0 ?

  • #314 Miguel Grinberg said 2019-07-02T21:03:46Z

    @jeex: This version is the rewrite. It is fully compatible with the current version of Flask.

  • #315 Brian Wcisel said 2019-07-17T12:48:41Z

    Greetings, I am using PyCharm and Python v 3.6 on Windows 10. Your demonstration is very helpful thus far but I was unable to run the microblog.py application without adding if name == 'main': app.run()

    Did I miss something in your demonstration or does my specific setup require something different?

    Has anyone else run into this problem?

  • #316 Miguel Grinberg said 2019-07-17T13:44:01Z

    @Brian: The method of running the application that I'm using in this tutorial involves running "flask run", not running the microblog.py script. If you want to match my method, you need to set up your PyCharm project to run the "flask run" command. The method that you are using will work mostly in the same way, so if you are comfortable running that way you can use that too.

  • #317 Mark said 2019-07-19T19:12:25Z

    I'm sorry to comment that using "app" for two concepts in this manner was necessarily confusing. It lead me to really need to re-understand what is going on. Maybe that's for the better, but that's a poor choice for a hello world app. Hope this feedback lands well.

    Thank you

  • #318 Elias said 2019-07-26T18:49:06Z

    Somehow, many commands are not working on AWS_C9. So, as soon as I changed to my local IDE it worked normally.

  • #319 Miguel Grinberg said 2019-07-26T22:21:24Z

    @Elias: you need to give me more details about the problem if you need my help.

  • #320 Cesar said 2019-08-06T03:11:26Z

    Great article, Miguel! I'm starting to learn web frameworks and Flask seems to be a good option, since python is a little familiar to me. Great explanation, It was very helpful!

  • #321 Travis said 2019-08-09T17:57:01Z

    I'm at the last step of hello world, "flask run" however it seems perhaps a step is missing. I'm running this in command line and of course there's no executable named flask... Here's the error:

    (venv) C:\Users\Travis\microblog>set FLASK_APP=microblog.py (venv) C:\Users\Travis\microblog>flask run 'flask' is not recognized as an internal or external command, operable program or batch file.

  • #322 Miguel Grinberg said 2019-08-09T18:40:21Z

    @Travis: this is a fairly recent Flask issue. See https://github.com/pallets/flask/issues/3327 for a workaround until the bug is fixed.

  • #323 Tom said 2019-08-11T15:00:15Z

    Hello Miguel,

    How should we configure the microblog.wsgi file so that we can use this application with apache2 and mod_wsgi?

    I've been following this tutorial however I've been having some problems to setup this application structure with Apache mod_wsgi. As per flask documentation https://flask.palletsprojects.com/en/1.1.x/deploying/mod_wsgi/#creating-a-wsgi-file

    Here's mine microblog.wsgi file:

    !/usr/bin/python3

    import sys import logging logging.basicConfig(stream=sys.stderr) sys.path.insert(0,"/var/www/microblog")

    from microblog import app as application application.secret_key = '1j4289j0129834j0129384j0'

    This file however as per the flask documentation requires init.py file to be present in the main application folder but we only have a microblog.py file containing: "from app import app". When I try to access the application from a browser via apache I am getting: Internal Server Error.

    These are the logs from /var/log/apache2/error.log: [Sun Aug 11 14:49:23.469535 2019] [wsgi:error] [pid 9354:tid 140103931434752] [remote 172.16.0.50:63410] mod_wsgi (pid=9354): Exception occurred processing WSGI script '/var/www/microblog/microblog.wsgi'. [Sun Aug 11 14:49:23.469549 2019] [wsgi:error] [pid 9354:tid 140103931434752] [remote 172.16.0.50:63410] Traceback (most recent call last): [Sun Aug 11 14:49:23.469562 2019] [wsgi:error] [pid 9354:tid 140103931434752] [remote 172.16.0.50:63410] File "/var/www/microblog/microblog.wsgi", line 8, in [Sun Aug 11 14:49:23.469579 2019] [wsgi:error] [pid 9354:tid 140103931434752] [remote 172.16.0.50:63410] from microblog import app as application [Sun Aug 11 14:49:23.469593 2019] [wsgi:error] [pid 9354:tid 140103931434752] [remote 172.16.0.50:63410] ImportError: No module named microblog

  • #324 Miguel Grinberg said 2019-08-11T20:46:53Z

    @Tom: I don't find Apache as user friendly, so I don't use it myself, and don't teach it. But in any case, the problem that you are having is likely that your Python import path does not have your top-level directory, so the microblog.py file in this directory cannot be imported. If you add your directory to the path the import will work.

  • #325 Not quite a pythonista said 2019-08-23T14:32:36Z

    This "Hello, World" tutorial no longer works; the flask run command will exit with "Error: Could not import 'microblog'." Apparently the CLI app can't find modules located in the current working directory. Reading GitHub issues, there are several potential solutions:

    FLASK_DEBUG=1 flask run (this works for me, not sure why) PYTHONPATH=. flask run python -m flask run Install the app once in editable mode with pip install --editable . and then flask run will work from that point forward (I haven't tested this)

Leave a Comment