DEV Community

Cover image for Flask Internals
Sm0ke
Sm0ke

Posted on • Originally published at blog.appseed.us

Flask Internals

Hello Coders!

This article presents a few commands we can execute inside the Flask Shell that might help us understand the structure and the business logic of a legacy web app. We might need this when we start working on a new project designed or coded in the past or when our own web app is getting bigger.

Thanks for reading! Topics covered:

  • πŸ‘‰ Flask - Short introduction
  • πŸ‘‰ Flask CLI (command line interface)
  • πŸ‘‰ List Registered Models
  • πŸ‘‰ List Table Columns

✨ Flask Intro

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. Getting started with Flask is pretty easy. Once we have Python3 installed and a modern code editor like VsCode or Atom we can write our first web app.

$ pip install flask
Enter fullscreen mode Exit fullscreen mode

The above command will install the latest version of Flask via PIP, the official package manager for Python.

# Contents of - app.py
from flask import Flask, escape, request

app = Flask(__name__)

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

Once the file is saved, we can invoke Flask magic using the command:

$ flask run
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Enter fullscreen mode Exit fullscreen mode

✨ Flask CLI

Flask provides a convenient way to interact with all app internals via a simple command-line interface powered by the Click package. To invoke the CLI, we need to execute the following command:

$ flask shell
>>>            # The shell is waiting for our commands
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Flask CLI - List Routes

$ flask shell
>>> from app import app
>>> app.url_map
Map([<Rule '/register.html' (HEAD, POST, GET, OPTIONS) -> register>,
 <Rule '/logout.html' (HEAD, GET, OPTIONS) -> logout>,
 <Rule '/sitemap.xml' (HEAD, GET, OPTIONS) -> sitemap>,
 <Rule '/login.html' (HEAD, POST, GET, OPTIONS) -> login>,
 <Rule '/static/<filename>' (HEAD, GET, OPTIONS) -> static>,
 <Rule '/<path>' (HEAD, GET, OPTIONS) -> index>,
 <Rule '/' (HEAD, GET, OPTIONS) -> index>])
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Flask CLI - Print static folder

$ flask shell
>>> from app import app
>>> app.static_folder
'D:\\work\\flask-material-kit\\app\\static'
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Flask CLI - Print templates folder

$ flask shell 
>>> from app import app
>>> app.template_folder
'templates'
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Flask CLI - List Database Models

The db object holds the SqlAlchemy interface and we will pull the information via this object.

$ flask shell
>>> from app import db      # <-- db is the object 
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ List All Tables

>>> from app import app, db
>>> db.metadata.tables
FacadeDict({'Users': Table('Users', MetaData(), Column('id', Integer(), table=<Users>, primary_key=True, nullable=False), Column('user', String(length=64), table=<Users>), Column('email', String(length=120), table=<Users>), Column('password', String(length=500), table=<Users>), schema=None)})
Enter fullscreen mode Exit fullscreen mode

In my project, we have a single Users table - let's take a look at the definition:

>>> from app import app, db
>>> db.metadata.tables['Users']
Table('Users', MetaData(), Column('id', Integer(), table=<Users>, primary_key=True, nullable=False), Column('user', String(length=64), table=<Users>), Column('email', String(length=120), table=<Users>), Column('password', String(length=500), 
table=<Users>), schema=None
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Flask CLI - List Table Columns

>>> from app import app, db
>>> for col in db.metadata.tables['Users'].columns:  
...     print ( col )
... 
Users.id
Users.user
Users.email
Users.password 
Enter fullscreen mode Exit fullscreen mode

✨ Free Sample - Material Kit

Curious minds can experiment and play with all the above commands using this open-source sample provided with database, authentication, SqlAlchemy ORM, and Docker support - Flask Material Kit.


Flask Material Kit - Bootstrap 5 Design.


Thanks for reading! For more resources, feel free to access:


Top comments (4)

Collapse
 
crearesite profile image
WebsiteMarket

Great content

Collapse
 
sm0ke profile image
Sm0ke

πŸš€πŸš€

Collapse
 
uithemes profile image
ui-themes

Can you suggest a real life scenarios where such introspection is useful?
Ty!

Collapse
 
sm0ke profile image
Sm0ke

Thanks for reading! Soemtimes we need to write custom commands for our app: create users from the console, for instance.
Also, if we write a low code project, we can add new fields for a table using the CLI.

πŸš€πŸš€