In this article, we’ll introduce Flask, a popular microframework for Python and the opposite of the giant that is Django. Flask makes it super easy to get started with Python.
The official Flask documentation states the following:
Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.
To explain this quote a bit further, Werkzeug is a Python utility library, and Jinja 2 is a template engine for Python.
Why Flask?
About a year ago, I was looking into another programming language outside of PHP. I’d been an active PHP developer for 10 years, and, to be honest, doing apps only in PHP gets a bit boring. It not having any standardized libraries or frameworks didn’t help either. I found myself spending half of my time reinventing the wheel just for the sake of reinventing something. Thinking I know better than the other PHP developers often leads to spending too much time on the project. This is very common in the PHP world — almost every other developer is building his own framework, and this can lead to certain types of chaos, but let’s not go there right now.
I was searching for something new, and at work we had just started to use Django for serious web development. Django, at that point, seemed like too big of a framework and I wanted something small that I could build upon. Then, I stumbled upon Flask, and I’ve been using it for most of my personal development projects since.
In this article, I will cover installing and configuring Flask and running a basic “hello world” example. Also, I’ll assume that you have a Linux machine installed (or a Mac) or that you’re running some sort of decent virtual machine, such as Homestead Improved.
Download and Install
To get started you will need Python 2.6 or higher. In Homestead Improved, this is a default.
First, for clean development, we need virtualenv
. As a Python developer, you will most likely build different applications. Different applications have different dependencies, maybe even different Python versions. To solve the problem of dependencies and used libraries stacking up on your machine, we use virtualenv
. Virtualenv
creates a separate environment for your application, so you can keep your environments fully isolated. For more info go to the docs.
Let’s install it:
sudo pip install virtualenv
You could even do something like this:
sudo apt-get install python-virtualenv
Once virtualenv is installed, create a new environment:
mkdir flaskproject
cd flaskproject
virtualenv env
New python executable in env/bin/python
Installing distribute............done.
Now you have a directory called flaskproject
. Inside that directory, you have another one (with your environment) called env
. To start using your environment, you need to “activate” it:
. env/bin/activate
Finally, let’s install Flask:
pip install Flask
You should see something like this:
Successfully installed Flask Werkzeug Jinja2 itsdangerous markupsafe
Cleaning up...
If you inspect your folder, notice that you’ll still see only your env directory. That’s OK, because Flask is installed inside your env
directory.
All the packages installed will be inside the site-packages
subdirectory:
env/lib/python2.6/site-packages
Or you can do pip list
, which will list all installed packages inside your environment. Don’t be afraid if you see more than just Flask, because Flask installs its own dependencies too:
pip list
You now have your environment and application ready to build upon.
Your first Flask application
Let’s create app.py
inside our directory:
from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route('/')
def main_method():
return "Hello everyone"
if __name__ == '__main__':
app.run()
If we run this code from the console, we’ll get something like this:
python app.py
Running on http://127.0.0.1:5000/
If you fire up your browser and go to the given address (or the vhost
you defined, if using VMs with Vagrant), you should see your message.
Let’s explain what’s going on:
from flask import Flask
app = Flask(__name__)
This imports the flask
library from Flask, and creates a new instance of the Flask
class.
While in development, I often have debug mode on. That’s what the app.debug = True
line is for. It gives me plenty of messages, automatically reloads the server when I change some files.
Next, we create a method that will return a simple string.
def main_method():
return "Hello everyone"
And above our method we use the routing decorator (@app.route('/')
) to specify a URL for it. Any request coming to /
will be redirected to main_method
. Simple, right?
This final piece of code checks if the script is being called directly, and not like an imported module. If that’s the case, it will run the code automatically:
if __name__ == '__main__':
app.run()
Fun with Templates
Now, let’s create a URL that will receive a parameter and pass it to the template, like so: /fun/params/optional_parameter
Add these lines to app.py
:
@app.route('/fun/urls/<param>')
def fun_url(param=None):
return render_template('fun_url.html')
In the first directive, we have a new route that will redirect to our new method. Because we defined a parameter at the end, our method expects that parameter. After that, we return the template with render_template
method.
If you save app.py
, and have an active server running it will break with an error of unknown method render_template
. This is because we’re calling a method that doesn’t exist — or at least it wasn’t imported. In our case, we still need to import this method.
On top of our file, add this:
from flask import render_template
By default, Flask expects template files to be located in the templates
directory relative to our app.py
. So, we need to create a new directory there:
mkdir templates
cd templates
touch fun_url.html
Now, restart th application:
python app.py
* Running on http://127.0.0.1:5000/
Then, open a URL like /fun/url/test
, and we should see an empty page. Please try to add something to that file and restart the server. We should be able to see our updated template file results.
Now let’s pass a parameter to the template. Change the render_template
line to the following:
return render_template('fun_url.html', fun_param=param)
With this, we tell the render_template
method to render our template and pass a param into it as fun_param
. Now open fun_url.html
and add this:
Parameter passed is: {{ fun_param }}
We should get this response after restarting the server:
http://127.0.0.1:5000/fun/url/test
Parameter passed is: test
http://127.0.0.1:5000/fun/url/test1
Parameter passed is: test1
Where to Go from Here
There are a lot more of things you can do with Flask. This is more of a beginner introduction so you can get a feel for how Flask works. When you start working with databases, user access, REST API — that’s where things get surprisingly simple. For now, the best place to start is the official Flask documentation.
Also, a really great article that covers almost everything you will need in further development is the Flask Mega-Tutorial.