Creating Custom cli Commands in Flask
Creating Custom cli Commands in Flask
The focus of this post is on using flask to build custom commands. Run is essentially a command that starts a function named run in the flask configuration files every time flask is started using the flask run command. Similar to the last example, if you have ever used flask migrate, you are likely familiar with flask DB migrate or upgrade. We will take the following actions to generate such a manual command that performs an action on the backend:
How does Flask build Custom Commands?
Step 1: Two fundamental libraries from Flask, click and with appcontext, are used to build commands. Create a command named "flask create" that will launch a database and add a straightforward table to it. Import those libraries as follows -
import click
from flask.cli import with_appcontext
These command line instructions are created by flask using the click library.
Step 2: Configure the database as follows-
db_path = f"sqlite:///{os.getcwd()}/database.sqlite3"
app.config['SQLALCHEMY_DATABASE_URI'] = db_path
Step 3: Next, let's make a straightforward table like shown:
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class MyTable(db.Model):
??__tablename__ = 'MyTable'
??id = db.Column(db.Integer, primary_key=True)
Since the goal of this post is to show how to build a command, this table will clearly not accomplish anything and only have one column. Instead, whenever you want to create a command, use the decorator first.
@click.command(name=’create’) – The value of the argument name shows the name of the custom command you want to build.
@with appcontext() – The function is referred to as being contained in the app because all app information is put into it when using with appcontext.
Step 4: Let's make the necessary file (app.py).
#app.py
#import necessary libraries
from flask import Flask
import click, os
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy
领英推荐
?
# initialize flask app
app = Flask(__name__)
?
# add database uri to app config
db_path = f"sqlite:///{os.getcwd()}/database.sqlite3"
app.config['SQLALCHEMY_DATABASE_URI'] = db_path
?
# init sqlalchemy with flask app
db = SQLAlchemy(app)
?
# define table schema
class MyTable(db.Model):
??__tablename__ = 'MyTable'
??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” cli command –
After Running “flask create” cli command –
We can clearly see the changes in explorer window “database.sqlite3” database created and in terminal window Table also created.?