This article aims to help beginners to accommodate with Flask, the popular web framework written in Python. To follow and learn something from this tutorial there is no need to have a previous programming background, the content will be presented in the most simple way possible, enhanced at some point with visual materials.
This tutorial will be periodically updated with new topics based on the new technology trends and your suggestions. Thank for reading!.
- What is Python
- What is Flask
- What is a web framework
- A curated list with Flask resources
- A short-list with Flask Starters
- Install Flask
- How to install dependencies
- Useful Flask modules
- Build a real Flask Application
- Deployment with Heroku and Docker
Python is an interpreted programming language (no compilation phase as for C/C++ programs) with high-level built-in data structures quite attractive for Rapid Application Development. The Python interpreter along with the standard libraries are available in source or binary form all major platforms (Linux, Windows or Mac).
To execute a Python program we need to have the Python interpreter available in the terminal. The first step is to access the official download page, download the installer for our operating system (Mac, Linux, M$ Windows) and execute it. If the installation goes well we should be able to access the interpreter from the terminal window (Powershell for windows, Xterm for Linux ...).
$ python --version $ Python 3.7.2
Please install the Python 3.x version, Python 2.x is deprecated and no longer supported by the Python foundation.
Flask is a Python web framework built with a small core and modularity in mind. It is classified as a microframework because it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components, and all those super necessary features are provided by third-party libraries developed by the team behind Flask or other developers from the community.
What is a Web Framework
The best definition I've found is this:
Web framework is a set of components and libraries designed to simplify your web development process. - Source HackerNoon.
Indeed, the goal of a Web Framework is to make our life easier and provide help regarding the repetitive configuration and modules required by multiple projects. Flask does this flawlessly.
A short and curated list. Feel free to suggest more in the comments.
- Flask - the official website
- Flask Docs - the official version
- Flask - Github repository
- Flask - a super popular tutorial on Full-Stack Python
- Flask Tutorials - supported by RealPython
- Flask Mega Tutorial by Miguel Grinberg
This section contains a few open-source UI-Ready starters already coded with a basic set of modules, helpers and deployment scrips.
- Flask Dashboard Black - Free admin panel - LIVE Demo
- Flask Dashboard Argon - MIT License - LIVE Demo
- Flask Dashboard Datta Able - LIVE Demo
- Flask Dashboard StarAdmin - LIVE Demo
- Flask Atlantis Dark - design by ThemeKita - LIVE Demo
For more open-source admin dashboards please access the AppSeed platform. The source code is published under the MIT license on Github (no account required to use the code).
The most easier way to install Flask is to use PIP (python package manager), which comes with Python3 binary distribution.
$ pip install Flask
To check the installation, we can open the python CLI and import
flask. If the module is properly installed, we should see no errors after import.
$ python $ Python 3.7.2 ... on win32 $ >>> from flask import Flask $ >>>
Each project has a list of dependencies usually saved in
requirements.txt file, located in the root of the project. This is a common practice visible in many opensource projects and adopted by many developers (me included). We can install the modules in two ways:
- globally, as we did in the previous section
- using a
Virtual Environment- the recommended way. Using a Virtual Environment (aka
VENV) the modules will be installed isolated in the workstation, usually called a
A simple use case to visualize the benefit of a VENV.
Imagine that we have two apps that use different versions of Flask. If The dependencies are installed globally, the dependencies will affect the set up for the other app. To avoid this use case, a virtual environment helps the developer to execute the app using an isolated environment, and both apps are usable in the same time, without dependencies errors.
Create a VENV Unix based systems
$ virtualenv --no-site-packages env $ source env/bin/activate
Create a VENV for Windows OS
$ # virtualenv --no-site-packages env $ # .\env\Scripts\activate
Once the VENV is created and activated, we can install the project requirements using
$ # Install requirements $ pip3 install -r requirements.txt
Flask uses third party libraries (or modules) to provide common features used in many projects. I will drop here a short-list with popular modules. Feel free to suggest more in comments, if I missed some.
- Flask-Login - create a user management flow and it takes care of the scary parts of authentication such as session management and dealing with cookies.
- Flask-Mail - Sending an email is important for a lot of application types, especially if you’re dealing with users.
- Flask-WTF - this module makes the forms processing a breeze.
- Flask-SQLAlchemy - The abstract object-oriented interface to many databases (MySql, SQLite, PostgreSQL).
Alembic - this module is super useful when we have a database in production and we need to update the DB Schema with new tables o mutate things on existing tables. In all this cases, Alembic will assist us to
migratethe old structure to the new one bu generating the necessary SQL and scripts.
Flask Dashboard Black, the app we will use as a sample to see something nice on the screen, is an open-source product coded in Flask on top of a beautiful UI Kit provided by Creative-Tim agency.
The source is available on Github and anyone can download the code and use it for hobby or commercial projects. In case you have issues using it, AMA in the comments.
The build instructions (saved also in the README file) are listed below:
$ # Get the code $ git clone https://github.com/app-generator/flask-black-dashboard.git $ cd flask-black-dashboard $ $ # Virtualenv modules installation (Unix based systems) $ virtualenv --no-site-packages env $ source env/bin/activate $ $ # Virtualenv modules installation (Windows based systems) $ # virtualenv --no-site-packages env $ # .\env\Scripts\activate $ $ # Install modules - SQLite Database $ pip3 install -r requirements.txt $ $ # OR with PostgreSQL connector $ # pip install -r requirements-pgsql.txt $ $ # Set the FLASK_APP environment variable $ (Unix/Mac) export FLASK_APP=run.py $ (Windows) set FLASK_APP=run.py $ (Powershell) $env:FLASK_APP = ".\run.py" $ $ # Set up the DEBUG environment $ # (Unix/Mac) export FLASK_ENV=development $ # (Windows) set FLASK_ENV=development $ # (Powershell) $env:FLASK_ENV = "development" $ $ # Start the application (development mode) $ # --host=0.0.0.0 - expose the app on all network interfaces (default 127.0.0.1) $ # --port=5000 - specify the app port (default 5000) $ flask run --host=0.0.0.0 --port=5000 $ $ # Access the dashboard in browser: http://127.0.0.1:5000/
If all goes well, we should see the dashboard, up & running in the browser. Please note that the app
redirects the guest users to the login screen. Please create a new user using the registration page and authenticate into the app. By default, the app uses SQLite to save login information, but we can switch to other databases like MySql or PostgresSQL with ease. Promise to document this in a separate article.
Flask Dashboard - User Profile Page
Flask Dashboard - User Registration Page
As mentioned, the app is released under the MIT license. Feel free to grab the code and add more features on top. A short-list with suggestions:
- Add another field in the user table - Adress
- Update the registration form to let users add the new information
- Display the new
Adressfield in the profile page
Coding an app in our environment is nice, but release it into the wild in the
internet is super rewarding, especially if is the first project. To deploy LIVE a Flask app, we have many options that depend on the server and the platform we are using.
The most simple way IMO is to use the Heroku platform. Of course, we need an account on the platform, and also the Heroku CLI installed in our environment. Please find below the steps to deploy the Flask Dashboard Black on Heroku:
$ # Get the code $ git clone https://github.com/app-generator/flask-black-dashboard.git $ cd flask-black-dashboard $ $ # Heroku Login $ heroku login $ $ # Create the app in Heroku platform $ heroku create # a random name will be generated by Heroku $ $ # Push the source code and trigger the deploy $ git push heroku master $ $ # Visit the deployed app in browser. $ heroku open
If all goes well, the app should be up & running. The database is automatically created and we just need to register a new user and log in.
This is not so user-friendly deployment method, but the app that we've mentioned as a sample comes with the necessary scripts to deploy the app instantly using Docker.
In case you want to fully understand the whole process behind the Docker deployment, feel free to access an article, entirely dedicated to this topic: Flask Dashboard - Execution with Docker. The basic steps are:
Get the code from Github, using Git
$ git clone https://github.com/app-generator/flask-black-dashboard.git $ cd flask-black-dashboard
Start the app in Docker
$ sudo docker-compose pull && sudo docker-compose build && sudo docker-compose up
http://localhost:5005 in your browser. The app should be up & running.
The deployment is not an easy topic to be digested by a beginner, and I prefer to provide a sample 100% configured and hide the real complexity covered by some nice scripts. To explain the deployment options, we need a full article that presents the possible and recommended architectures.
For a particular deploy configuration, feel free to AMA in the comments. I'll be glad to help and provide an extra opinion.
Thanks for reading! Yours, with much respect!
Claim your page on DEV before someone else does
Level up every day