SoFunction
Updated on 2024-11-17

python framework flask knowledge summary

I. Flask Blueprint Catalog

We previously wrote the Flask project are their own organization of the directory structure, in fact, Flask has its official recommended directory structure, the following is a project structure in line with the official recommendations of Flask small applications directory example, as follows:

在这里插入图片描述

As shown in the figure, this is a good directory structure, one layer at a time, first is the app directory, which is our main application directory, which has a __init__.py file, the contents of which are as follows:

app/

from flask import Flask
from . import acc_bp
from . import user_bp

def create_app():
    my_app = Flask(__name__)
    my_app.register_blueprint(acc_bp)
    my_app.register_blueprint(user_bp)

    return my_app

app/__init__.py

__init__.pyIt's a function that builds the app and registers the blueprints in the views.

Next look at the static directory, this directory from the literal meaning can be understood, is our static static file storage directory.

Then there is the templates directory, the template storage directory.

The views directory, where the main character finally appears, holds the view function files, that is, ourBlueprintEach file is a Blueprint, as follows:
views/

from flask import Blueprint

acc_bp = Blueprint('acc', __name__)

@acc_bp.route("/acc")
def accfunc():
    return "my_app.acc"

views/

views/

from flask import Blueprint

user_bp = Blueprint('user', __name__)

@user_bp.route("/login")
def user_login():
    return "my_app.user"

views/

Next up is the crucial one, the project's startup file, which reads as follows:

from app import create_app

my_app = create_app()

if __name__ == '__main__':
    my_app.run()

II. Flask-SQLAlchemy

1. Installation

pip install Flask-SQLAlchemy

2, next based on the above Flask project, we want to add Flask-SQLAlchemy to make the project come alive!

2.1 Adding the Flask-SQLAlchemy Third-Party Component

app/__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy    # Import SQLAlchemy from Flask-SQLAlchemy

db = SQLAlchemy()   # Instantiate SQLAlchemy
# Note: The code that instantiates SQLAlchemy must be introduced before the blueprints are

# Introduce blueprints
from . import acc_bp
from . import user_bp


def create_app():
    my_app = Flask(__name__)

    # Initialize app configuration, specifically for SQLAlchemy
    my_app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:@127.0.0.1:3306/wll?charset=utf8"
    my_app.config["SQLALCHEMY_POOL_SIZE"] = 5    # Connection pool size for SQLAlchemy
    my_app.config["SQLALCHEMY_POOL_TIMEOUT"] = 15   # Connection timeout for SQLAlchemy
    my_app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    db.init_app(my_app)  # Initialize SQLAlchemy , which essentially reads out the above configuration

    my_app.register_blueprint(acc_bp)
    my_app.register_blueprint(user_bp)

    return my_app

app/__init__.py

2.2 Create (ORM model files) in app directory

app/

from app import db

# from  import declarative_base
# Base = declarative_base()
# Previously we had to do this when we created a data table, however Flask-SQLAlchemy has wrapped the Base for us, the

# Create the users table
class Users():
    __tablename__ = 'users'
    # __table_args__ = {"useexisting": True}

    # Flask-SQLAlchemy also wraps Column, Integer, String, etc. for us!
    id = (, primary_key=True)
    name = ((32))
    password = ((32))


if __name__ == '__main__':
    from app import create_app
    my_app = create_app()
    # Here's where you'll want to review the Flask application context management
    # Offline scripts.
    with my_app.app_context():
        db.drop_all()        # Delete all tables
        db.create_all()      # Create tables

app/

2.3 Login View Functions

Remember when we manually opened the session in sqlalchemy db_session

 from  import sessionmaker
   Session = sessionmaker(engine)
   db_session = Session()

Not anymore, because Flask-SQLAlchemy does the session opening for us too!

from flask import Blueprint, request, render_template

user_bp = Blueprint('user', __name__)

from  import Users
from app import db


@user_bp.route("/login", methods=['GET', 'POST'])
def user_login():
    if  == 'POST':
        username = ('username')
        password = ('password')

        # Remember when we manually opened the session in sqlalchemy db_session
        # from  import sessionmaker
        # Session = sessionmaker(engine)
        # db_session = Session()
        # Not anymore, because Flask-SQLAlchemy does the session opening for us too!
        (Users(name=username,password=password))
        ()

        # Query
        user_obj = ( == username and  == password).first()
        if user_obj:
            return f"{user_obj.name}Login Successful"

    return render_template("")

views/

2.4 Landing page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<form method="post" action="">
  <input type="text" name="username">
  <input type="password" name="password">
  <input type="submit">
</form>
</body>
</html>

templates/

III. Flask-Script

1. Installation

pip install Flask-Script

2, next and then based on the above project, add Flask-Script, so that we can start the project with the command

In fact, this part is to pave the way for the following Flask-Migrate, Flask-Script as the name suggests is the script of Flask. Do you remember Django's startup command? Yes, it's python runserver, in fact, Flask can also do, based on Flask-Script can be.

3.1 Adding Flask-Script to a Flask Project

from flask_script import Manager    # Importing Managers in Flask-Script

from app import create_app

my_app = create_app()

manager = Manager(my_app)    # Make the app support manager

if __name__ == '__main__':
    # my_app.run()
    ()   # Replace the original my_app.run() and you're done!


3.2 Starting a Flask Project with Commands

python  runserver

在这里插入图片描述

3.3 Start the Flask project and change the configuration parameters (IP address and port number to listen on)

python  runserver -h 0.0.0.0 -p 9527

在这里插入图片描述

3.4 Advanced Operations - Customizing Script Commands

Mode 1: @

from flask_script import Manager    # Importing Managers in Flask-Script

from app import create_app

my_app = create_app()

manager = Manager(my_app)    # Make the app support manager

@
def runflask(arg):
    # my_app.run() # release this sentence item humg live
    print(arg)


if __name__ == '__main__':
    # my_app.run()
    ()   # Replace the original my_app.run() and you're done!


Execute the command:

python  runflask 22

The results are shown below:

 在这里插入图片描述

Execute the command:

python  talk -n you -s ferocious
python  talk --name me --say ferocious

在这里插入图片描述

IV. Flask-Migrate

1. Installation

pip install Flask-Migrate

2, continue based on the above project, so that the Flask project to support makemigration and migrate

4.1 Add Flask-Migrate (note: Flask-Migrate depends on the Flask-Script component) to the project

from flask_script import Manager    # Importing Managers in Flask-Script
# Import Migrate and MigrateCommand from Flask-Migrate
# These two things are simply trying to add a few commands and directives to Flask-Script
from flask_migrate import Migrate, MigrateCommand

from app import create_app

my_app = create_app()

manager = Manager(my_app)    # Make the app support manager

from app import db
Migrate(my_app, db)  # Since it's a database migration, tell him where the database is and tell him which apps to support #
# Then tell the manager that there's a new command, which is stored in MigrateCommand.
manager.add_command("database", MigrateCommand)  # When you have a database command in a command, go to MigrateCommand and look for the relationship.
"""
Database Migration Instructions:
python database init
python database migrate # The Django equivalent of makemigration.
python database upgrade # The Django equivalent of migrate.
"""


@
def runflask(arg):
    # my_app.run() # release this sentence item humg live
    print(arg)


@("-n", "--name", dest="name")
@("-s", "--say", dest="say")
def talk(name, say):
    print(f"{name}really{say}")


if __name__ == '__main__':
    # my_app.run()
    ()   # Replace the original my_app.run() and you're done!


4.2 Execute database initialization commands

python  database init

在这里插入图片描述

At this point you will notice a migrations directory in your project directory as shown below:

 在这里插入图片描述 

4.3 Execute database migration instructions

python  database migrate     # The Django equivalent of makemigration.
python  database upgrade     # equivalent toDjangohit the nail on the head migrate

The results are shown below:

在这里插入图片描述

At this point you will notice that there is a USERS table in the database.

to this article on the python framework flask knowledge summarizes the article is introduced to this, more related python flask content please search my previous posts or continue to browse the following related articles I hope you will support me in the future!