Creating Custom cli Commands in Flask

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 –


No alt text provided for this image



After Running “flask create” cli command –


No alt text provided for this image


We can clearly see the changes in explorer window “database.sqlite3” database created and in terminal window Table also created.?


No alt text provided for this image


要查看或添加评论,请登录

Skill Gain的更多文章

  • Do you know how to use Scroll View?

    Do you know how to use Scroll View?

    UIScrollView is a widget or component in UIKit that allows users to scroll through content that is larger than the…

  • Machine Learning

    Machine Learning

    MACHINE LEARNING Machine learning is a field of study that has gained a lot of attention in recent years due to its…

  • JWT Authentication

    JWT Authentication

    Why JWT? When we are working on PHP we can use SESSION for authentication, but when we will use API in a third-party…

  • CSRF Protection in Flask

    CSRF Protection in Flask

    Let's carry out a quick Flask project to demonstrate how you can manually safeguard your data with CSRF protection. In…

  • Dynamic URLs Variable Rule in Flask

    Dynamic URLs Variable Rule in Flask

    Dynamic URLs Variable Rule in Flask This article will go through Python's Flask-Variable Rule. With no database…

  • Query Parameters with Multi-Value in Flask A

    Query Parameters with Multi-Value in Flask A

    Python-based Flask is a micro-framework. It is well-known for creating RESTful APIs since it is lightweight and simple…

  • Introducing the React Hook for Sound Effects "use-sound"

    Introducing the React Hook for Sound Effects "use-sound"

    Introducing the React Hook for Sound Effects "use-sound" Use the React hook use-sound to play sound effects. This is a…

  • How to Create Spinners In Android?

    How to Create Spinners In Android?

    Android Spinner is a view that resembles a drop-down menu and is used to select a single option from a list of options.…

  • Useful Custom Hooks That You Need To Add Into Your React Project (Part II)

    Useful Custom Hooks That You Need To Add Into Your React Project (Part II)

    Useful Custom hooks that You need to add into your React Project : Hooks are great for extracting logic into reusable…

  • A Brief on React Helmet (Part 1)

    A Brief on React Helmet (Part 1)

    React Helmet Every website developer hopes that his or her website will show up first in the browser's search results…

社区洞察

其他会员也浏览了