Flask Black Dashboard
Open-source seed project with Black Dashboard design
Open-source Flask Dashboard generated by the AppSeed platform on top of Black Dashboard, a modern dark-themed design from Creative-Tim. Flask codebase is provided with database, ORM, modular codebase, and deployment scripts.
Flask Black Dashboard - Open-source Starter

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.

Environment

To use the stater, Python3 should be installed properly in the workstation. If you are not sure if Python is properly installed, please open a terminal and type python --version. The full list with dependencies and tools required to build the app:
    Python3 - the programming language used to code the app
    GIT - used to clone the source code from the Github repository
    Basic development tools (g++ compiler, python development libraries ..etc) used by Python to compile the app dependencies in your environment.
Check Python version (using the terminal)
1
$ # Check Python version
2
$ python --version
3
Python 3.7.2 # <--- All good
Copied!
Check GIT command tool (using the terminal)
1
$ # Check git
2
$ git --version
3
$ git version 2.10.1.windows.1 # <--- All good
Copied!

Build the app

To built and start the app locally, follow the steps:
Get the source code
Change the current directory to source code directory and folow this set up
1
$ # Create Virtualenv (Unix based systems)
2
$ virtualenv env
3
$ source env/bin/activate
4
$
5
$ # Create Virtualenv (Windows based systems)
6
$ # virtualenv env
7
$ # .\env\Scripts\activate
Copied!
Install requirements
1
$ pip3 install -r requirements.txt
Copied!
Set up Environment
1
$ # Set the FLASK_APP environment variable
2
$ (Unix/Mac) export FLASK_APP=run.py
3
$ (Windows) set FLASK_APP=run.py
4
$ (Powershell) $env:FLASK_APP = ".\run.py"
Copied!
Start the application
1
$ # Run the application
2
$ flask run
3
$
4
$ # Access the app in browser: http://127.0.0.1:5000/
Copied!
At this point, we should see the app running in the browser. By default, Flask starts on port: 5000. We can force Flask using another port by using --port option:
1
$ # Start Flask using cutom port
2
$ flask run --port=9999
3
$
4
$ # Access the app in browser: http://127.0.0.1:9999
Copied!
By default, the app will redirect guest users to the login page. To access the private pages:
    Create a new user using the registration page
    Authenticate using the login page

App Codebase (simplified)

Starter uses a simple codebase (no Blueprints) with a structure presented below:
1
< PROJECT ROOT >
2
|
3
|-- app/ # Implements app logic
4
| |-- base/ # Base Blueprint - handles the authentication
5
| |-- home/ # Home Blueprint - serve UI Kit pages
6
| |
7
| __init__.py # Initialize the app
8
|
9
|-- requirements.txt # Development modules - SQLite storage
10
|-- requirements-mysql.txt # Production modules - Mysql DMBS
11
|-- requirements-pqsql.txt # Production modules - PostgreSql DMBS
12
|
13
|-- .env # Inject Configuration via Environment
14
|-- config.py # Set up the app
15
|-- run.py # Start the app - WSGI gateway
16
|
17
|-- ************************************************************************
Copied!

The bootstrap flow

    run.py loads the .env file
    Initialize the app using the specified profile: Debug or Production
      If env.DEBUG is set to True the SQLite storage is used
      If env.DEBUG is set to False the specified DB driver is used (MySql, PostgreSQL)
    Call the app factory method create_app defined in app/init.py
    Redirect the guest users to the Login page
    Unlock the pages served by the home blueprint for authenticated users
.env (saved in the root of the project)
1
# File: `.env`
2
3
DEBUG=True # Enable/Disable the development environment
4
5
SECRET_KEY=S3cr3t_Key # The Key used by Flask to encrypt session information
6
7
# Database production settings (If DEBUG=False)
8
9
DB_ENGINE=postgresql # DBMS
10
DB_NAME=appseed-flask # Database Name
11
DB_HOST=localhost # Database Host
12
DB_PORT=5432 # Database Port
13
DB_USERNAME=appseed # DB Username
14
DB_PASS=pass # DB Password
15
Copied!
run.py (simplified version)
1
# File: run.py
2
3
DEBUG = config('DEBUG', default=True)
4
5
# Create the WSGI app, using the app factory pattern
6
app = create_app( app_config )
7
8
# Migrate automaticaly the app using Flask Migrate library
9
Migrate(app, db)
Copied!
App constructor: app/__init__.py constructs the app by putting together a short-list of things:
    Invoke SQLAlchemy and build the interface to the database
    Invoke and inject the Login Manager into the app
    Load the configuration from config.py file
    Register blueprints: home and base
    Create app tables (if not yet created)
    Return the WSGI app

App Configuration

The configuration file config.py (in the root of the project) define a dual configuration controlled via the .env file ( DEBUG variable)
DebugConfig - default configuration used for development
This configuration becomes active if .env file has the DEBUG file set to True
1
# Development/Debug configuration
2
3
# Set up the App SECRET_KEY
4
SECRET_KEY = config('SECRET_KEY', default='S#perS3crEt_007')
5
6
# This will create a file in <app> FOLDER
7
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'db.sqlite3')
8
SQLALCHEMY_TRACK_MODIFICATIONS = False
9
Copied!
During the first request, the SQLite database and tables are automatically created.
Hint: to visualize the SQLite database content an external tool should be installed: DB Browser for SQLite it might be a good choice.
ProductionConfig - production configuration
This configuration becomes active if .env file has the DEBUG file set to False
1
# Production configuration
2
3
SESSION_COOKIE_HTTPONLY = True
4
REMEMBER_COOKIE_HTTPONLY = True
5
REMEMBER_COOKIE_DURATION = 3600
6
7
# PostgreSQL database
8
SQLALCHEMY_DATABASE_URI = '{}://{}:{}@{}:{}/{}'.format(
9
config( 'DB_ENGINE' , default='postgresql' ),
10
config( 'DB_USERNAME' , default='appseed' ),
11
config( 'DB_PASS' , default='pass' ),
12
config( 'DB_HOST' , default='localhost' ),
13
config( 'DB_PORT' , default=5432 ),
14
config( 'DB_NAME' , default='appseed-flask' )
15
)
16
Copied!
In this configuration profile, the database defaults to a PostgreSQL DBMS. Make sure the .env has the right credentials to access the database.

App Tables

The file app/base/models.py (Base Blueprint) defines the table(s) used by the application. Being a simple starter, by default the following tabes are defined:
    Table #1 - User with fields:
      Id - Primary key, unique
      user - Store the username
      email - The email address
      password - Hashed password

App Forms

The file app/base/forms.py (Base Blueprint) defines the table(s) used by the application. Being a simple starter, by default the following forms are defined:
    Form #1 - LoginForm with fields:
      username
      password
    Form #2 - RegisterForm with fields:
      username - used to authenticate
      email - email address
      password - used to authenticate

App Routing

The routing rules are defined by Base and Home blueprints as specified below. This is the public zone of the app.
Base Blueprint - routing file app/base/routes.py
    /login route is resolved by login() method
    /register route is resolved by register() method
    /logout route calls the logout_user() defined in flask_login
Registered ERROR handlers
    404 Error - Page not found
    403 Error - Access Forbidden
    500 Error - Internal Error
Home Blueprint - routing file app/home/routes.py
This blueprint will serve requested pages from app/home/templates directory to authenticated users. The authentication status is checked by @login_required decorator.
    /<template> route resolved by route_template()
      If a requested page is not found a default 404 page is returned to the user

Pages & Assets

Pages and all assets defined in the UI Kits are served by the app using both blueprints:
    Home Blueprint manage the static assets - app/base/static/assets
    Home Blueprintstore the layout master pages, HTML chunks (footer. header, scripts) and login, registration pages
    Base Blueprint serves the HTML pages (index, page-404, etc) and the rest of the pages defined in the UI kit.
App / Base Blueprint
The Base blueprint handles the authentication (routes and forms) and assets management. The structure is presented below:
1
< PROJECT ROOT >
2
|
3
|-- app/
4
| |-- home/ # Home Blueprint
5
| |-- base/ # Base Blueprint
6
| |-- static/
7
| | |-- <css, JS, images> # CSS files, Javascripts files
8
| |
9
| |-- templates/ # UI Templates
10
| |
11
| |-- includes/ #
12
| | |-- navigation.html # Top menu component
13
| | |-- sidebar.html # Sidebar component
14
| | |-- footer.html # UI Footer
15
| | |-- scripts.html # JS Scripts used by all pages
16
| |
17
| |-- layouts/ # Master pages
18
| | |-- base-fullscreen.html # Used by Authentication pages
19
| | |-- base.html # Used by common pages
20
| |
21
| |-- accounts/ # Authentication pages
22
| |-- login.html # Login page
23
| |-- register.html # Registration page
Copied!
App / Home Blueprint
The Home blueprint handles UI Kit pages for authenticated users. This is the private zone of the app - the structure is presented below:
1
< PROJECT ROOT >
2
|
3
|-- app/
4
| |-- base/ # Base Blueprint
5
| |-- home/ # Home Blueprint
6
| |
7
| |-- templates/ # UI Kit Pages
8
| |
9
| |-- index.html # Default page
10
| |-- page-404.html # Error 404 - mandatory page
11
| |-- page-500.html # Error 500 - mandatory page
12
| |-- page-403.html # Error 403 - mandatory page
13
| |-- *.html # All other HTML pages
Copied!

Data Structures

The Flask starter exposes a short-list with data structures used globally across the app:

current_user object

Constructed by Flask-Login can be used to detect if the current request is executed by an authenticated user or not. The object has global visibility and can be used in all app controllers and handlers but also in views.
How it works
app/base/models.py define the callback functions required by Flask-Login library:
1
# File: app/base/models.py
2
3
@login_manager.user_loader
4
def user_loader(id):
5
return User.query.filter_by(id=id).first()
6
7
@login_manager.request_loader
8
def request_loader(request):
9
username = request.form.get('username')
10
user = User.query.filter_by(username=username).first()
11
return user if user else None
12
Copied!
Usage in contoler (Sample file)
1
2
def sample_method(path):
3
4
# Redirect guests users to login page
5
if not current_user.is_authenticated:
6
return redirect(url_for('login'))
Copied!
Usage in view
1
<!-- The Usage of <current_user> object -->
2
{% if current_user.is_authenticated %}
3
4
<!-- Html chunk rendered for authenticated users-->
5
6
{% else %}
7
8
<!-- Html chunk rendered for guests users-->
9
10
{% endif %}
Copied!

Resources & Support

Last modified 5mo ago