DEV Community

Cover image for Flask Cheat Sheet - And FREE samples
Sm0ke
Sm0ke

Posted on • Updated on • Originally published at blog.appseed.us

Flask Cheat Sheet - And FREE samples

Hello Coders,

This article is just another Flask Cheat Sheet that might help beginners to speed up their learning curve and the rest of our audience with some nice production-ready samples. 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.



1# - 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 aims to keep the core of its framework small but highly extensible.


2# - Install Flask

$ pip install Flask
Enter fullscreen mode Exit fullscreen mode

3# - Creating an isolated environment

$ python -m venv flask_env
Enter fullscreen mode Exit fullscreen mode

Activate virtual environment

$ source flask_env/bin/activate
Enter fullscreen mode Exit fullscreen mode

Deactivate virtual environment

$ deactivate
Enter fullscreen mode Exit fullscreen mode

4# - A super simple Flask app

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return f'Hello from Flask!'
Enter fullscreen mode Exit fullscreen mode

5# - Start the app

$ env FLASK_APP=hello.py flask run
 * Serving Flask app "hello"
 * Running on http://127.0.0.1:5000/
Enter fullscreen mode Exit fullscreen mode

6# - Object-Based Configuration

Create a new config file in the project root:

PROJECT_ROOT/app/config.py

Add content using OOP and class inheritance


class BaseCfg(object):
    SECRET_KEY = 'SuperS3cretKEY_1222'
    DEBUG = False
    TESTING = False

class DevelopmentCfg(BaseCfg):
    DEBUG = True
    TESTING = True

class TestingCfg(BaseCfg):
    DEBUG = False
    TESTING = True

class ProductionCfg(BaseCfg):
    SECRET_KEY = 'HvFDDcfsnd__9nbCdgsada' 
    DEBUG = False
    TESTING = False
Enter fullscreen mode Exit fullscreen mode

Let's use the configuration:

Update PROJECT_ROOT/app/__init__.py to use it:

from flask import Flask
from app import config

app = Flask(__name__)
app.config.from_object(config.DevelopmentCfg) # <--- Magic line
Enter fullscreen mode Exit fullscreen mode

7# - Render page using Jinja

The Flask controller

from flask import Flask, render_template
app = Flask(__name__)

@app.route("/test")
def template_test():
    return render_template('template.html', my_string="Jinja Works!!")

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

The HTML template

<html>
  <head>
    <title>Flask Template Example</title>
  </head>
  <body>
    <div class="container">
      <p>Result: {{my_string}}</p>
    </div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

By accessing http://localhost:5000/test in the browser, we should see:

Status: Jinja Works


8# - Using Flask shell

$ flask shell
Enter fullscreen mode Exit fullscreen mode

9# - Define a model with SQLAlchemy using SQLite

Create PROJECT_ROOT/app/models.py with the following content:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):

    id       = db.Column(db.Integer,     primary_key=True)
    user     = db.Column(db.String(64),  unique = True)
    email    = db.Column(db.String(120), unique = True)
    password = db.Column(db.String(500))

    def __init__(self, user, email, password):
        self.user       = user
        self.password   = password
        self.email      = email
Enter fullscreen mode Exit fullscreen mode

Update PROJECT_ROOT/app/config.py with the Database connection string:

class BaseCfg(object):
    SECRET_KEY = 'SuperS3cretKEY_1222'
    DEBUG = False
    TESTING = False

    # This will create a file in <app> FOLDER
    SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
Enter fullscreen mode Exit fullscreen mode

Update PROJECT_ROOT/app/__init__.py to use the model:

from flask_sqlalchemy import SQLAlchemy
...

db = SQLAlchemy  (app) # flask-sqlalchemy
Enter fullscreen mode Exit fullscreen mode

The User tables can be created using flask shell:

$ flask shell
>>> from app import db
>>> db.create_all()
Enter fullscreen mode Exit fullscreen mode

The second method is to create the tables automatically at the first request using a hook provided by Flask.

Update PROJECT_ROOT/app/__init__.py as below:

# Setup database
@app.before_first_request
def initialize_database():
    db.create_all()
Enter fullscreen mode Exit fullscreen mode

10# - List users via Flask shell

$ flask shell
>>> from app.models import User
>>> User.query.all()
# HERE we should see all users 
Enter fullscreen mode Exit fullscreen mode

Let's see this theory applied to these open-source Flask samples:


Flask Pixel UI Kit

Open-Source Web App coded in Flask Framework - features:

  • UI Kit: Pixel UI kit by Themesberg
  • UI-Ready, Jinja2 templating
  • SQLite database, Flask-SQLAlchemy ORM
  • Session-Based auth flow (login, register)


Flask Pixel UI Kit - Open-source Flask starter, provided by AppSeed.


Flask Datta Able

Flask Dashboard generated by the AppSeed platform on top of Datta Able (free version), a modern Bootstrap 4 dashboard template. The Flask codebase is provided with authentication, database, ORM, and deployment scripts.


Flask Datta Able.


Flask Volt Free

Open-Source Flask Dashboard coded with basic modules, database, ORM and deployment scripts on top of Volt Dashboard (free version), a modern Bootstrap dashboard design.

Volt is a free and open source Bootstrap 5 Admin Dashboard featuring over 100 components, 11 example pages and 3 customized plugins. Volt does not require jQuery as a dependency meaning that every library and script's are jQuery free.


Flask Volt Free.


Flask Dashboard Argon

Argon Dashboard is built with over 100 individual components, giving you the freedom of choosing and combining. All components can take variations in color, that you can easily modify using SASS files.

You will save a lot of time going from prototyping to full-functional code, because all elements are implemented. This Dashboard is coming with pre-built examples, so the development process is seamless, switching from our pages to the real website is very easy to be done.


Flask Argon Dashboard.


Thanks for reading! For more resources please access:


Thank you! Btw, my (nick) name is Sm0ke and I'm pretty active also on Twitter.

Top comments (9)

Collapse
 
crearesite profile image
WebsiteMarket

Nice, Thanks!

Collapse
 
sm0ke profile image
Sm0ke

Yw! :)

Collapse
 
ironcladdev profile image
Conner Ow

I love using flask!
Thanks for making the cheatsheet!

Collapse
 
sm0ke profile image
Sm0ke

Yw, Thank you for reading this post.

Collapse
 
madhunimmo profile image
✨Nimmo✨

Great post

Collapse
 
yokotobe profile image
yokotobe

Thanks for sharing

Collapse
 
sm0ke profile image
Sm0ke

Yw!

Collapse
 
uithemes profile image
ui-themes

Cool. Would be nice to have something related to Flask Migration.

Collapse
 
sm0ke profile image
Sm0ke

Noted! I will add the content asap.