Sunday, November 17, 2024
Google search engine
HomeLanguagesCreating Custom Commands in Flask

Creating Custom Commands in Flask

This article revolves around how to create custom commands in flask. Every time one runs flask using flask run, run is actually a command which initiates a function called run in flask config files. Similarly, if you have ever used something like flask migrate then you are probably familiar with flask DB migrate or upgrade. To create such a manual command that does some action on backend, we will follow some steps – 

How to create Custom Commands in Flask?

Step 1: Commands are created using two primary libraries – click and with_appcontext library of flask. Now let’s create a command called “flask create” that should initiate a Database and create a simple table in that DB

import click
from flask.cli import with_appcontext

click is the library that flask uses to create these commands on the command line.

Step 2:  Add Database configuration – 

from flask_sqlalchemy import SQLAlchemy
app.config['SQLALCHEMY_DATABASE_URI']="sqlite://db.sqlite3"

Step 3: Then let’s create a simple table as shown :

class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)

So this table obviously won’t do anything, it will be having just one column in it as the purpose of this article is to demonstrate how to create a command so anytime you want to create a command first you use the decorator @click.command(name=’create’) (here value of the argument name tells the name of the custom command you want to create).

@with_appcontext() – with_appcontext puts all the app information in this function so the function is referred to be contained in the app.

Step 4 – Let’s create the required file

Python3




# import required libraries
from flask import Flask
import click
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
 
# initialize flask app
app = Flask(__name__)
 
# initialize Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://db.sqlite3'
 
# create Database
db = SQLAlchemy(app)
 
# add table to Database
class MyTable(db.Model):
    id = db.Column(db.Integer, primary_key=True)
 
# create command function
@click.command(name='create')
@with_appcontext
def create():
    db.create_all()
 
# add command function to cli commands
app.cli.add_command(create)


Before Running Flask create – 

After running Flask Create – 

Tables in the database – 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments