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
from flask import Flask
import click
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
class MyTable(db.Model):
id = db.Column(db.Integer, primary_key = True )
@click .command(name = 'create' )
@with_appcontext
def create():
db.create_all()
app.cli.add_command(create)
|
Before Running Flask create –
After running Flask Create –
Tables in the database –
Last Updated :
29 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...