Getting started with the Flask web framework
What is Flask?
Flask is a Python web framework built with a small core and easy-to-extend philosophy that was originally designed and developed by Armin Ronacher in 2010 and became the most popular Python web framework in 2018.
What is a web framework?
A web framework is a code library that makes web development faster and easier by providing common patterns for building reliable, scalable and maintainable web applications. Since the turn of the century, it is common practice for web development projects to use an existing web framework except in very unusual situations. Other than Flask, popular web frameworks include Django, ASP.NET, Laravel, and Ruby on Rails.
Web frameworks provide functionality in their code or through extensions to perform common operations required to run web applications. These common operations include:
- URL routing
- Input form handling and validation
- HTML, XML, JSON, and other output formats with a templating engine
- Database connection configuration and persistent data manipulation through an object-relational mapper (ORM)
- Web security against Cross-site request forgery (CSRF), SQL Injection, Cross-site Scripting (XSS) and other common malicious attacks
- Session storage and retrieval
Some web frameworks, like Django, take the ‘batteries included’ approach where everything is provided in the framework with tight integration. Other frameworks, like Flask, take a different approach and provide minimal functionality with easy extensibility. For example, rather than bake it into the framework, Flask enables developers to work with non-relational databases by incorporating external Python libraries.
What is web development and how is Flask related?
Web development is the umbrella term for conceptualizing, creating, deploying and operating web applications and application programming interfaces for the Web.
Flask is a web framework, not a web development language. Flask expects files written in Python which Flask will then process.
Prior to installing Flask, we need to install Python. Python can easily be installed using the
npm package manager, a.k.a. ‘Node Package Manager’, and the
npm install command.
npm install Python
Starting with Python 3.4, the
pip module, a.k.a. ‘preferred installer program’, is included by default with the Python binary installers. We will use pip to easily install Flask.
pip install Flask
Along with the Flask library, this will also install all of Flask’s dependencies including Click, itsdangerous, Jinja2, MarkupSafe, and Werkzeug. We can see these dependencies using pip and the
pip list command.
The output of the
pip list command should look like the image below in a completely clean environment. We can create a completely clean environment using the
virtualenv package thatis also included by default with the Python binary installers.
Two key dependencies that I’d like to call out are
Flask depends on the Jinja template engine and the Werkzeug WSGI toolkit. These dependencies will also be installed when we install Flask.
Werkzeug includes a comprehensive web application library that implements WSGI. As per the WSGI documentation, WSGI, i.e. the ‘Web Server Gateway Interface’, is a specification that describes how a web server communicates with web applications and how web applications can be chained together to process one request. Flask inherits its high WSGI usage and compliance from Werkzeug. Flask wraps Werkzeug, using it to handle the details of WSGI.
Jinja is a template language that renders the pages your application serves. using a template engine. Template engines take in tokenized strings and produce rendered strings with values in place of the tokens as output. This allows developers to generate desired content types, such as HTML or XML, while using some of the data and programming constructs such as conditionals and for loops to manipulate the output. Template files that are created by developers and then processed by the template engine consist of prewritten markup and template tag blocks where data is inserted. In a Flask application, Jinja will generate the HTML output response when an HTTP request comes in for a particular URL.
Building our basic Flask application
It’s quick and easy to get a basic application built in Flask. The code below is a fully functional Flask application that I wrote in under one minute. I break down this code further at the end of this section. To use this code as boilerplate code for your own Flask application, you can find the source code on my GitHub.
from flask import FlasksimpleApp = Flask(__name__)@simpleApp.route(‘/’)
return ‘<h1 style=”color: red”>Hiyee! I am a simple Flask application.</h1>’if __name__ == ‘main’:
The key pieces of the code above the following:
- First, we need to import the
Flaskclass from the
- Next, we need to create an instance of the
Flaskclass. We will name it
simpleApp. The first argument that we will pass in our instantiation of the class is the name of our application’s module. Since we are using a single module, we pass
__name__as the value because this name will be different depending on if our application is started as a standalone application or imported as a module. This value is needed so that knows where to look for resources like templates and static files.
- Next, we use the
route()decorator to tell Flask the URL that should trigger our main function.
- Next, we create our main function and name it
home()function returns some basic HTML with inline styling. This is what will be displayed in the client, e.g. our browser.
- Finally, we save the file and give it a name. I have saved this file as
flask-quickstart.pybut any filename will due as long as it is not
flask.pybecause this would conflict with Flask itself.
Now that we have defined our main function, we are ready to run our Flask application. If you would like to do this on your own, you can clone the source code from my GitHub, install Flask and its dependencies as described in the previous section, and follow the instructions to run the application in the next section.
Running our basic Flask application
For development purposes, Flask provides a built-in server. To run the application on this built-in server, we first point our terminal to our Flask project’s directory. From within this directory, we need need to tell our terminal the application to work with by exporting the
FLASK_APP environment variable:
Next, we can run the application by using Flask.
Alternatively, we could run the application using Python and the -m option to run the Flask module as a script.
python -m flask run
Either way, running the Flask application will spin up a local WSGI web server accessible on port 5000.
When you run the application for the first time, you will notice that a new folder is created called
__pycache__ in the root folder of our application’s project. This is a folder containing your Python source code compiled down to bytecode that is ready to be executed. This process is necessary because Python is an interpreted language which means that an interpreter must compile our Python to bytecode before it can be run. The file in our
__pycache__ folder is a bytecode-compiled version of our application’s files. This file helps our program start faster. This folder and its content will be updated as we update our application.
For production purposes, the built-in WSGI web server is not a suitable option due to limited scaling capabilities. In this case, we can look hosted and non-hosted options. For getting started, I recommend a hosted option. These options include Heroku, Google App Engine, AWS Elastic Beanstalk, Azure, and PythonAnywhere.
If you have been working along with this blog then congratulations! You have built your first Flask application and have deployed it to a WSGI web server running locally on your machine.
What to do now?
When learning Flask, I found the following checklist to be a great learning map:
- Get a basic understanding of how Flask works.
- Work through a detailed Flask tutorial.
- Study open source examples that use Flask so that you can take parts of those projects and reuse the code in your own Flask application.
- Build a first iteration of your Flask application.
- Learn Flask’s deployment options to make your application accessible on the web.
And, above all, remember to keep at it — one drop at a time!
About the author
Colin Kraczkowsky recently returned to web development after exploring the craft of product management. Colin’s professional history includes working in both enterprise and start up environments to code web and mobile applications, launch new products, build mockups and prototypes, analyze metrics, and continuously innovate.
In his spare time, Colin can be found checking out the latest Alite camp kit for a weekend away in Big Sur, planning his next line down a mountain at Kirkwood, or surfing the Horror section on Netflix. Colin is currently located in San Francisco, California.
Connect with Colin — https://www.linkedin.com/in/colinkraczkowsky