Hello Coders,
This article presents a short and comprehensive introduction to Flask and a curated list with Flask Templates provided with basic modules, database, ORM, and deployment scrips on top of modern UI Kits. For newcomers, Flask is a lightweight web application framework written in Python. Sometimes classified as a microframework, Flask provides a lightweight codebase that can be easily extended to become an API, a simple web app, or a complex eCommerce platform.
Thank you! Content provided by AppSeed - App Generator.
Topics covered and resources
- What is Flask
- How to get started with Flask
- Flask - a super simple application
- Flask Template System - Jinja Template engine
- (Free) Flask Pixel UI - product page
- (Free) Flask Datta Able - product page
- (Free) Flask Argon - product page
- (Free) Flask Volt - product page
What is Flask
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Classified as a microframework, Flask is written in Python and it does not require particular tools or libraries. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions.
If we have Python installed we can see Flask in action on our browser in less than one minute. Let's make a short test:
1# - Install Flask
$ pip install Flask
2# - Use your preferred editor to code a minimal Flask app
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return f'Hello from Flask!'
Save the file and ...
3# - Start the app and see it in the browser
$ env FLASK_APP=hello.py flask run
* Serving Flask app "hello"
* Running on http://127.0.0.1:5000/
By visiting the app in the browser we should see that warm message.
Flask - More than "Hello World"
With Flask we can easily code a simple, multi-page website using a Bootstrap template. Our next sample will be coded on top of Pixel UI Kit - an open-source accessibility first design.
Please find below a possible codebase structure for our project. I said "possible" because Flask is highly configurable and empowers the developer with the freedom to structure the app without any constraints.
< PROJECT ROOT >
|
|--- app/__init__.py
|--- app/
| | --- <static/assets>
| | |--- <css>
| | |--- <Js>
| | |--- <img>
| |
| | --- <templates>
| |---<includes> # Page chunks, components
| | | --- navigation.html # Top bar
| | | --- sidebar.html # Left sidebar
| | | --- scripts.html # JS scripts common to al
| | | --- footer.html # The common footer
| |
| |---<layouts> # App Layouts
| |
| index.html # The default page
| *.html # All other pages
|
|--- requirements.txt
|
|--- run.py
|
|-----------------------------
Let's iterate over the relevant files:
- run.py - the entry point used to start the application requirements.txt - a file that specifies all dependencies (for now is just Flask)
- app - the application folder where we will add our code
- app/init.py - This file is required to let us use the app as a Python Package
- app/static - this folder will contain design assets: JS, css and images.
- templates - the directory with pages, layouts, and components used by Flask to generate some nice pages for us
Before we start using templates in Flask, let's code a simple app that use strings to render a page, without templates:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return '''
<html>
<head>
<title>Simple App</title>
</head>
<body>
<h1>Hello</h1>
<p>From Flask - no templates</p>
</body>
</html>'''
Basically, we are returning a string formatted as a simple HTML page with all standard sections (HEAD, body tags). If the project should render more than one line on every page, it might be a good idea to start using a template system to have a well-organized project, easy to maintain and use by us and others.
Jinja Template System
What is Jinja - Jinja is a library for Python used by popular web frameworks like Flask and Django to serve HTML pages in a secure and efficient way. Using a template engine is a common practice in web development, no matter the language or framework used to code the web application.
How to install Jinja
$ pip install jinja2
We can test and play with the Jinja engine directly in the Python console:
>>> from jinja2 import Template
>>> t = Template("Jinja {{ token }}!")
>>> t.render(token="works")
u'Jinja works!'
Jinja Template System - A few reasons to use it
Work Less
Jinja allows us to reuse components (aka common HTML chunks) in many pages and contexts with minor changes. Imagine that we have a footer with some links and contact information, common to all pages in a web application. Using Jinja we can define a separate file named footer.html and we can reuse it with a simple include:
footer.html definition
<footer class="footer">
<div class=" container-fluid ">
<span>
© YourCompany;
</span>
<span>
Contact: bill [ @ ] microsoft.com
</span>
</div>
</footer>
footer.html usage in a final page:
<head>
<title>
Jinja Template - Cheat Sheet | Dev.to
</title>
</head>
<body>
<div class="content">
Some cool content
</div>
<!-- The magic include line -->
{% include 'footer.html' %}
</body>
</html>
Template Inheritance
Inheritance, in Jinja context, means to define a base template
that defines the basic structure of all subsequent child templates. This master template can be inherited
via extends
directive to build variations (new pages).
A real sample
Parent HTML - saved as base.html
<html>
<head>
<title>My Jinja {% block title %}{% endblock %} </title>
</head>
<body>
<div class="container">
<h2>This is from the base template</h2>
<br>
{ block content }{ endblock }
<br>
</div>
</body>
</html>
The Child template - saved as child.html
{ extends "base.html" }
{ block title } MySample { endblock }
{ block content }
Cool content here
{ endblock }
When Jinja loads child.html
, the { extends }
block informs the engine to merge the base.html
template with the content provided by child.html
.
-
{ block title }
becomes MySample -
{ block content }
becomes Cool content here
Generated HTML (by Jinja)
<html>
<head>
<title>My Jinja MySample</title>
</head>
<body>
<div class="container">
<h2>This is from the base template</h2>
<br>
Cool content here
<br>
</div>
</body>
</html>
Jinja - Render Lists
Jinja supports control structures like if/else
, for loops
to manipulate lists and dictionaries.
List definition
# Define a simple list
users = ['user1','user2', 'user3']
Jinja code snippet
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
Generated HTML
<h1>Members</h1>
<ul>
<li>user1</li>
<li>user2</li>
<li>user3</li>
</ul>
For
loops can be checked for emptiness with a simple else
, as below:
Jinja code snippet
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% else %}
<li><em>no users found</em></li>
{% endfor %}
</ul>
Generated HTML
<h1>Members</h1>
<ul>
<li>no users found</li>
</ul>
Jinja - HTML Escaping
Escaping is useful when HTML is generated and the injected content might contain >
, <
, &
, or "
. Escaping in Jinja works by piping the variable through the |e filter:
Jinja code snippet
{{ content|e }} <!-- content might contain unsafe chars -->
Filter sections allow to apply regular Jinja filters on a block of template data - the syntax:
Jinja code snippet
{% filter upper %}
uppercase me
{% endfilter %}
Generated HTML
UPPERCASE ME
Jinja Math
Jinja allows you to compute values. Here are some samples:
{{ 1 + 1 }} will render 1
{{ 1 / 2 }} will render 0.5
{{ 11 % 7 }} will render 4
Flask Template - Pixel UI
Pixel UI Kit (Free version) designed by Themesberg and coded in Flask Framework with SQLite database, SqlAlchemy ORM and authentication.
Pixel is a free, fully responsive and modern Bootstrap 4 UI Kit that will help you build creative and professional websites. Use our components and sections, switch some Sass variables to build and arrange pages to best suit your needs.
- Flask Pixel UI - product page
- Flask Pixel UI PRO - more pages, components, LIVE Support
Flask - Datta Able
Datta Able Free Dashboard designed by CodedThemes coded in Flask Framework with SQLite database, SQLAlchemy ORM and authentication.
Datta Able Bootstrap Lite is the most stylised Bootstrap 4 Lite Admin Template, around all other Lite/Free admin templates in the market. It comes with high feature-rich pages and components with fully developer-centric code. Before developing Datta Able our key points were performance and design.
- Flask Datta Able - product page
- Flask Datta Able PRO - more pages, components, LIVE Support
Flask Template - Argon
Argon Dashboard designed by Creative-Tim coded in Flask with authentication, ORM, Blueprints, deployment scripts for Docker, HEROKU, and Gunicorn/Nginx stack.
Argon Dashboard is built with over 100 individual components, giving you the freedom of choosing and combining. Every component has multiple states for colors, styles, hover, focus, that you can easily access and use.
- Flask Template Argon - product page
- Flask Template Argon PRO - more pages, components, LIVE Support
Flask Template - Volt
Volt Admin Dashboard (free version) designed by Themesberg and coded in Flask Framework with SQLite database, SqlAlchemy ORM and authentication.
Volt Dashboard is a free and open source Bootstrap 5 Admin Dashboard featuring over 100 components, 11 example pages and 3 plugins with Vanilla JS. There are more than 100 free Bootstrap 5 components included some of them being buttons, alerts, modals, datepickers and so on.
- Flask Template Volt - product page
- Flask Template Volt PRO - more pages, components, LIVE Support
Thanks for reading! For more resources please access:
- Getting Started with Python
- More Flask Dashboards - provided by AppSeed
Thank you! Btw, my (nick) name is Sm0ke and I'm pretty active also on Twitter.
Top comments (3)
Nice piece👍👍
There so many more better and free ones out there. I've tried most of yours and they are to full with stuff that's unneeded.
A simple Google search will return many starters that provide useful features and nice patterns.
Regarding the ones listed here, the feature set is minimal: just database, ORM, authentication, and deploy.
If you have the time and see this message, feel free to elaborate a little bit.
Thanks in advance!
P.S. Starters are generated also in a simple Flask codebase without database and ORM, just Flask and deploy scripts:
Jinja Templates - Github index.
Happy coding!