This is post 1 of the Python Flask Tutorial Series
What is Python Flask
Flask is a Micro Web Framework which is written in Python and is based on the Werkzeug Toolkit and the Jinja2 Template Engine.
Flask is super lightweight, and you import the modules as you need them, from some research some say that Flask is more designed for smaller applications whereas Django is designed for your larger applications.
a Good read on the [Differences and Performance Comparison]. With that being said, if you are planning with scale I am pretty sure that Flask can handle big applications, but it probably depends what your application is doing. More Detailed Discussion on Reddit.
Hello World in Python Flask
In this post we will be creating a “Hello, World” application to demonstrate how easy it is to run a Flask Appliation.
The only requirement you need to run this app, would be to to have
pip installed so that we can install the
Flask package which is needed.
Creating your Traditional Hello World App
We will install flask globally, but will write up a future post on how to setup a virtual environment for you application. Install the flask package:
The code for the Hello World Flask Application:
1 2 3 4 5 6 7 8 9 10
Save the above code as
app.py and then run the application as follows:
1 2 3 4 5 6
It’s Running What Now?
We can see that our application is running on 127.0.0.1 and listening on port: 5000, if you point your browser to this URL, you will be returned with: Hello, World!
1 2 3 4 5 6 7 8
Explaining the Application Code
- First, we imported the
Flaskclass from the flask module, using:
from flask import Flask
- Then we instantiate our application from the Flask class:
app = Flask(__name__)using our module’s name as a parameter, where our app object will use this to resolve resources. We are using
__name__, which links our module to our app object.
- Next up we have the
@app.route('/')decorator. Flask uses decorators for URL Routing.
- Below our decorator, we have a
view function, this function will be executed when the
/route gets matched, in this case returning
- The last line starts our server, and from this example it runs locally on
debug is enabled, so any error details will be logged directly in the browser. This is only recommended for test/dev and not for production as you can make your service vulnerable for hackers.
Let’s Extend our Hello World App
We would like to add the route ‘/movie’ which will return a random movie name:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Making a GET Request on the ‘/movie’ route:
This was just a basic example and will be covering more topics in detail at a further stage.
Next up, setting up our Python Environment, with Virtual Environment (virtualenv)
All posts related to this tutorial series will be listed under Python Flask Tutorial Series tag.