2012-05-07T06:05:40Z

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

(Great news! There is a new version of this tutorial!)

This is the first article in a series where I will be documenting my experience writing web applications in Python using the Flask microframework.

NOTE: This article was revised in September 2014 to be in sync with current versions of Python and Flask.

Here is an index of all the articles in the series that have been published to date:

My background

I'm a software engineer with double digit years of experience developing complex applications in several languages. I first learned Python as part of an effort to create bindings for a C++ library at work.

In addition to Python, I've written web apps in PHP, Ruby, Smalltalk and believe it or not, also in C++. Of all these, the Python/Flask combination is the one that I've found to be the most flexible.

UPDATE: I have written a book titled "Flask Web Development", published in 2014 by O'Reilly Media. The book and the tutorial complement each other, the book presents a more updated usage of Flask and is, in general, more advanced than the tutorial, but some topics are only covered in the tutorial. Visit http://flaskbook.com for more information.

The application

The application I'm going to develop as part of this tutorial is a decently featured microblogging server that I decided to call microblog. Pretty creative, I know.

These are some of the topics I will cover as we make progress with this project:

  • User management, including managing logins, sessions, user roles, profiles and user avatars.
  • Database management, including migration handling.
  • Web form support, including field validation.
  • Pagination of long lists of items.
  • Full text search.
  • Email notifications to users.
  • HTML templates.
  • Support for multiple languages.
  • Caching and other performance optimizations.
  • Debugging techniques for development and production servers.
  • Installation on a production server.

So as you see, I'm going pretty much for the whole thing. I hope this application, when finished, will serve as a sort of template for writing other web applications.

Requirements

If you have a computer that runs Python then you are probably good to go. The tutorial application should run just fine on Windows, OS X and Linux. Unless noted, the code presented in these articles has been tested against Python 2.7 and 3.4, though it will likely be okay if you use a newer 3.x release.

The tutorial assumes that you are familiar with the terminal window (command prompt for Windows users) and know the basic command line file management functions of your operating system. If you don't, then I recommend that you learn how to create directories, copy files, etc. using the command line before continuing.

Finally, you should be somewhat comfortable writing Python code. Familiarity with Python modules and packages is also recommended.

Installing Flask

Okay, let's get started!

If you haven't yet, go ahead and install Python.

Now we have to install Flask and several extensions that we will be using. My preferred way to do this is to create a virtual environment where everything gets installed, so that your main Python installation is not affected. As an added benefit, you won't need root access to do the installation in this way.

So, open up a terminal window, choose a location where you want your application to live and create a new folder there to contain it. Let's call the application folder microblog.

If you are using Python 3, then cd into the microblog folder and then create a virtual environment with the following command:

$ python -m venv flask

Note that in some operating systems you may need to use python3 instead of python. The above command creates a private version of your Python interpreter inside a folder named flask.

If you are using any other version of Python older than 3.4, then you need to download and install virtualenv.py before you can create a virtual environment. If you are on Mac OS X, then you can install it with the following command:

$ sudo easy_install virtualenv

On Linux you likely have a package for your distribution. For example, if you use Ubuntu:

$ sudo apt-get install python-virtualenv

Windows users have the most difficulty in installing virtualenv, so if you want to avoid the trouble then install Python 3. If you want to install virtualenv on Windows then the easiest way is by installing pip first, as explaned in this page. Once pip is installed, the following command installsvirtualenv`:

$ pip install virtualenv

We've seen above how to create a virtual environment in Python 3. For older versions of Python that have been expanded with virtualenv, the command that creates a virtual environment is the following:

$ virtualenv flask

Regardless of the method you use to create the virtual environment, you will end up with a folder named flask that contains a complete Python environment ready to be used for this project.

Virtual environments can be activated and deactivated, if desired. An activated environment adds the location of its bin folder to the system path, so that for example, when you type python you get the environment's version and not the system's one. But activating a virtual environment is not necessary, it is equally effective to invoke the interpreter by specifying its pathname.

If you are on Linux, OS X or Cygwin, install flask and extensions by entering the following commands, one after another:

$ flask/bin/pip install flask
$ flask/bin/pip install flask-login
$ flask/bin/pip install flask-openid
$ flask/bin/pip install flask-mail
$ flask/bin/pip install flask-sqlalchemy
$ flask/bin/pip install sqlalchemy-migrate
$ flask/bin/pip install flask-whooshalchemy
$ flask/bin/pip install flask-wtf
$ flask/bin/pip install flask-babel
$ flask/bin/pip install guess_language
$ flask/bin/pip install flipflop
$ flask/bin/pip install coverage

If you are on Windows the commands are slightly different:

$ flask\Scripts\pip install flask
$ flask\Scripts\pip install flask-login
$ flask\Scripts\pip install flask-openid
$ flask\Scripts\pip install flask-mail
$ flask\Scripts\pip install flask-sqlalchemy
$ flask\Scripts\pip install sqlalchemy-migrate
$ flask\Scripts\pip install flask-whooshalchemy
$ flask\Scripts\pip install flask-wtf
$ flask\Scripts\pip install flask-babel
$ flask\Scripts\pip install guess_language
$ flask\Scripts\pip install flipflop
$ flask\Scripts\pip install coverage

These commands will download and install all the packages that we will use for our application.

"Hello, World" in Flask

You now have a flask sub-folder inside your microblog folder that is populated with a Python interpreter and the Flask framework and extensions that we will use for this application. Now it's time to write our first web application!

After you cd to the microblog folder, let's create the basic folder structure for our application:

$ mkdir app
$ mkdir app/static
$ mkdir app/templates
$ mkdir tmp

The app folder will be where we will put our application package. The static sub-folder is where we will store static files like images, javascripts, and cascading style sheets. The templates sub-folder is obviously where our templates will go.

Let's start by creating a simple init script for our app package (file app/__init__.py):

from flask import Flask

app = Flask(__name__)
from app import views

The script above simply creates the application object (of class Flask) and then imports the views module, which we haven't written yet. Do not confuse app the variable (which gets assigned the Flask instance) with app the package (from which we import the views module).

If you are wondering why the import statement is at the end and not at the beginning of the script as it is always done, the reason is to avoid circular references, because you are going to see that the views module needs to import the app variable defined in this script. Putting the import at the end avoids the circular import error.

The views are the handlers that respond to requests from web browsers or other clients. In Flask handlers are written as Python functions. Each view function is mapped to one or more request URLs.

Let's write our first view function (file app/views.py):

from app import app

@app.route('/')
@app.route('/index')
def index():
    return "Hello, World!"

This view is actually pretty simple, it just returns a string, to be displayed on the client's web browser. The two route decorators above the function create the mappings from URLs / and /index to this function.

The final step to have a fully working web application is to create a script that starts up the development web server with our application. Let's call this script run.py, and put it in the root folder:

#!flask/bin/python
from app import app
app.run(debug=True)

The script simply imports the app variable from our app package and invokes its run method to start the server. Remember that the app variable holds the Flask instance that we created it above.

To start the app you just run this script. On OS X, Linux and Cygwin you have to indicate that this is an executable file before you can run it:

$ chmod a+x run.py

Then the script can simply be executed as follows:

./run.py

On Windows the process is a bit different. There is no need to indicate the file is executable. Instead you have to run the script as an argument to the Python interpreter from the virtual environment:

$ flask\Scripts\python run.py

After the server initializes it will listen on port 5000 waiting for connections. Now open up your web browser and enter the following URL in the address field:

http://localhost:5000

Alternatively you can use the following URL:

http://localhost:5000/index

Do you see the route mappings in action? The first URL maps to /, while the second maps to /index. Both routes are associated with our view function, so they produce the same result. If you enter any other URL you will get an error, since only these two have been defined.

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

And with this I conclude this first installment of this tutorial.

For those of you that are lazy typists, you can download the code from this tutorial below:

Download microblog-0.1.zip.

Note that you still need to install Flask as indicated above before you can run the application.

What's next

In the next part of the series we will modify our little application to use HTML templates.

I hope to see you in the next chapter.

Miguel

350 comments

  • #226 Miguel Grinberg said 2014-07-11T02:45:53Z

    @Yecid: the run.py script goes in your main application folder, not on flask\Scripts. Also remember to always use backward slashes if you are using the Windows command line.

  • #227 Peter Goldsborough said 2014-07-12T02:13:39Z

    Hey, I was having problems with your code, getting H12 Time out requests all the time. I found the solution and wanted to share this with you, might wanna change your run.py()?: http://stackoverflow.com/questions/16020749/heroku-app-runs-locally-but-gets-h12-timeout-error-uses-a-package

  • #228 armash said 2014-07-14T09:07:20Z

    hey..when i execute python run.py it shows me error that app from app import app "NO MODULE NAMED app"

  • #229 Sergey Smirnov said 2014-07-25T14:01:18Z

    \flask\Scripts\python.exe \tutorial/run.py Traceback (most recent call last): File "/tutorial/run.py", line 1, in from app import app File "\tutorial\app__init__.py", line 4, in from app import views ImportError: cannot import name views

    The file views.py is definitly in /app folder. Can you explaine me what are you doing in init.py? app in 3rd line is a Flask object. Is it some kind of import from Flask object&

  • #230 Miguel Grinberg said 2014-07-25T16:17:56Z

    @Sergey: you need to be in the main project folder, you seem to be one directory up. Put your virtual environment inside tutorial and start the app from there.

  • #231 Benny Eggerstedt said 2014-07-25T23:57:04Z

    Hi Miguel,

    I'm planning to let a web application, that after watching your PyCon videos would now be based on Flask, work with another service that has an XML-based API to extract information. Would you still use Flask for that or combine it with e.g. python-requests? I still need to go through your tutorial steps, but I didn't feel like finding an answer to that question yet. Thanks for all your work and have a good day, Benny

  • #232 Miguel Grinberg said 2014-07-26T01:11:00Z

    @Benny: these are two different tasks. To request data from an external API you can use requests, that would be my choice. But then you probably have your own API that other clients will consume, and for that you should use Flask.

  • #233 zchumager said 2014-08-02T04:45:17Z

    I got this error message

    ImportError: No module named flask

    do you have any idea?

  • #234 Daniel van Flymen said 2014-08-05T09:10:46Z

    In views.py why do you have to import app (from app import app) when we are importing views.py to init.py which has app already?

  • #235 Miguel Grinberg said 2014-08-05T17:52:01Z

    @Daniel: each Python module needs to import what it needs from other modules or packages. This is confusing between init.py and views.py because there is a circular dependency there: views.py needs to import app, so that it can use the app.route decorator. On the other side, init.py needs to import all the routes in views.py so that they are registered with Flask.

  • #236 Adebayo said 2014-08-19T12:54:43Z

    Thank you

  • #237 SK Ko said 2014-08-21T02:49:16Z

    I'm a student from South Korea. Thank you for good posting!!! I've learned a lot!!!

  • #238 Danny McAlerney said 2014-08-27T06:57:21Z

    This blog post series is an exceptional, potent, and intuitive guide to programming with Python and Flask.

    Mercy, I'm thankful. I'm probably going to send you some sort of Edible Arrangement...with pineapple and sticks.

  • #239 sibusiso said 2014-08-29T08:52:33Z

    Hi Miguel, Ca i run this code on python interpreter rather than virtual environment. I am working on windows machine and get an error that there is no module called app. I am very new to python and i am learning along.

    thank you

  • #240 Miguel Grinberg said 2014-08-30T05:55:47Z

    @sibusiso: you can, but note that the virtual environment has a Python interpreter as well. Running on Windows should not be a problem.

  • #241 Bob Brown said 2014-08-30T23:35:21Z

    For the folks who are running their PCs at home and setting up their sandbox in the cloud, they can add "host='0.0.0.0'" to their app.run() arguments and then they could see the web page from their home browser instead of having to try and get some browser other than lynx to run on their remote server.

    BOb

  • #242 Pranav said 2014-09-26T14:19:38Z

    i am having a little problem in understanding the third code.you wrote "from app import app" while there is no file as app in app-directory.does it has to do something with "init.py" .please explain

  • #243 Miguel Grinberg said 2014-09-28T06:13:26Z

    @Pranav: this is the way packages work in Python. The symbols that a package exports are declared in the init.py file. See the official Python documentation for details.

  • #244 Chris said 2014-09-30T21:19:18Z

    Miguel, Is it possible to follow this tutorial by using the online environment Runnable? I am trying to build a complete website that uses a database and everything, but I am unable to install flask or bottle personally because I am using a school computer, (I can do it at home, but then there's no point in me attending the class) and the IT guys who fix these computers have no idea how to install flask. tl;dr: Can't install flask, can I use Runnable instead?

  • #245 Miguel Grinberg said 2014-10-01T06:27:09Z

    @Chris: this article explains how to install flask, you don't have to ask the IT guys. In any case, if you wan to try an online service, the one I know that could work is PythonAnywhere. Runnable does not seem to have generic Python support, they only have Django.

  • #246 dave said 2014-10-02T21:31:30Z

    Thanks for the tutorial.

    You state that "run.py" should be in the root folder. May I suggest that you be more specific and write exactly which folder that is. I had to put it in the "flask" folder and modify it slightly to:

    !bin/python

    from app import app app.run(debug=True)

    dave

  • #247 miguelgilrosas said 2014-10-05T20:19:20Z

    Thank you for this tutorial!

  • #248 Deven said 2014-10-08T19:53:39Z

    Miguel, this is the best tutorial I've seen for any language I have wanted to learn. It's detailed enough to help noobs like myself and it explains what's happening so that i can really understand the underlying mechanisms at work. I can't thank you enough for the work you've put into writing this up.

  • #249 Stephanie said 2014-10-17T01:18:49Z

    Why not use a requirements.txt file to install your python packages to make it easier to install packages? Then you could just use pip install -r conf/requirements.txt (for example).

  • #250 Miguel Grinberg said 2014-10-17T05:55:15Z

    @Stephanie: there is a requirements.txt file in the project, so you are free to use it. But here in the article I prefer to list the packages that are used to give an idea of what the tutorial is about.