Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the flask framework

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Today, I would like to share with you the relevant knowledge about how to use the flask framework. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

I. Flask Blueprint Catalog

We have established a directory structure and take a look at it layer by layer. The first is the app directory, which is our main application directory, where there is a _ _ init__.py file, which contains the following contents:

App/init.py

From flask import Flaskfrom .views.acc import acc_bpfrom .views.user import user_bpdef create_app (): my_app = Flask (_ _ name__) my_app.register_blueprint (acc_bp) my_app.register_blueprint (user_bp) return my_appapp/__init__.py

_ _ init__.py is a function that builds app and registers the blueprints in views.

Next, look at the static directory, which can be understood literally as our static static file storage directory.

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

Views directory, the protagonist finally appeared, here is the view function file, that is, our Blueprint, each file is a Blueprint, as follows:

Views/acc.py

From flask import Blueprintacc_bp = Blueprint ('acc', _ _ name__) @ acc_bp.route ("/ acc") def accfunc (): return "my_app.acc" views/acc.py

Views/user.py

From flask import Blueprintuser_bp = Blueprint ('user', _ _ name__) @ user_bp.route ("/ login") def user_login (): return "my_app.user" views/user.py

Then there is a key file, manager.py, the startup file of the project, which is as follows:

Manager.py

From app import create_appmy_app = create_app () if _ _ name__ = ='_ main__': my_app.run () manager.py II, Flask-SQLAlchemy

1. Installation

Pip install Flask-SQLAlchemy

2. Based on the Flask project above, we will add Flask-SQLAlchemy to make the project lively.

2.1 add third-party components to Flask-SQLAlchemy

App/__init__.py

From flask import Flaskfrom flask_sqlalchemy import SQLAlchemy# import SQLAlchemydb = SQLAlchemy () # instantiate SQLAlchemy# Note: the code that instantiates SQLAlchemy must introduce blueprint from .views.acc import acc_bpfrom .views.user import user_bpdef create_app (): my_app = Flask (_ _ name__) # initialize app configuration before introducing blueprint Configure my_app.config ["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:@127.0.0.1:3306/wll?charset=utf8" my_app.config ["SQLALCHEMY_POOL_SIZE"] = 5 # SQLAlchemy connection pool size my_app.config ["SQLALCHEMY_POOL_TIMEOUT"] = 15 # SQLAlchemy connection timeout my_app.config ["SQLALCHEMY_TRACK_MODIFICATIONS"] specifically for SQLAlchemy = False db.init_app (my_app) # initialize SQLAlchemy The essence is to read out the above configuration my_app.register_blueprint (acc_bp) my_app.register_blueprint (user_bp) return my_appapp/__init__.py2.2 and set up models.py (ORM model file) in the app directory.

App/models.py

From app import db# from sqlalchemy.ext.declarative import declarative_base# Base = declarative_base () # We used to do this when creating datasheets, but Flask-SQLAlchemy has already encapsulated Base for us, that is, db.Model# created users datasheet class Users (db.Model): _ _ tablename__ = 'users' # _ table_args__ = {"useexisting": True} # Flask-SQLAlchemy also encapsulated Column,Integer for us. String, etc. Id = db.Column (db.Integer Primary_key=True) name = db.Column (db.String (32)) password = db.Column (db.String (32)) if _ _ name__ = ='_ main__': from app import create_app my_app = create_app () # here you want to review the Flask application context management # offline script: with my_app.app_context (): db.drop_all ( ) # Delete all tables db.create_all () # create table app/models.py2.3 login view function

Do you remember that we manually opened the session db_session in sqlalchemy

From sqlalchemy.orm import sessionmaker Session = sessionmaker (engine) db_session = Session ()

Not now, because Flask-SQLAlchemy has also done the job of opening the session for us.

From flask import Blueprint, request, render_templateuser_bp = Blueprint ('user', _ name__) from app.models import Usersfrom app import db@user_bp.route ("/ login", methods= [' GET' 'POST']) def user_login (): if request.method =' POST': username = request.form.get ('username') password = request.form.get (' password') # remember that we manually opened the session in sqlalchemy db_session # from sqlalchemy.orm import sessionmaker # Session = sessionmaker (engine) # db_session = Session () # not used now Because Flask-SQLAlchemy has also done the work for us to open the session db.session.add (Users (name=username) Password=password) db.session.commit () # query user_obj = Users.query.filter (Users.name = = username and Users.password = = password) .first () if user_obj: return f "{user_obj.name} login succeeded" return render_template ("login.html") views/user.py2.4 landing page Title templates/login.html III, Flask-Script

1. Installation

Pip install Flask-Script

2. Then, based on the above project, add Flask-Script so that we can start the project with commands

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

Start Flask project python manager.py runserver3.3 start Flask project with command And change the configuration parameters (listening IP address and port number) python manager.py runserver-h 0.0.0.0-p 95273.4 Advanced Operations-Custom script Command

Method 1: @ manager.command

From flask_script import Manager # Import Managerfrom app import create_appmy_app = create_app () manager = Manager (my_app) # Let app support manager@manager.commanddef runflask (arg): # my_app.run () # release this item humg live print (arg) if _ _ name__ = ='_ main__': # my_app.run () manager.run () # Just replace the original my_app.run (), manager.py.

Execute the command:

Python manager.py runflask 22

Execute the command:

Python manager.py talk-n you-s good python manager.py talk-- name me-- say good four, Flask-Migrate

1. Installation

Pip install Flask-Migrate

2. Continue to support makemigration and migrate in the Flask project based on the above project

Add Flask-Migrate (Note: Flask-Migrate depends on the Flask-Script component) to the project from flask_script import Manager# Import Flask-Script Manager# Import Flask-Migrate Migrate and MigrateCommand# to put it bluntly, I just want to add a few commands and instructions to Flask-Script from flask_migrate import Migrate MigrateCommandfrom app import create_appmy_app = create_app () manager = Manager (my_app) # Let app support managerfrom app import dbMigrate (my_app, db) # since it is a database migration, you have to tell him where the database is, and tell him which app# to support and then tell manager that there is a new instruction. This new instruction is stored in MigrateCommand manager.add_command ("database", MigrateCommand) # when the database instruction appears in your command Then go to MigrateCommand to find the corresponding database migration instructions: python manager.py database init python manager.py database migrate # is equivalent to makemigrationpython manager.py database upgrade # in Django, equivalent to migrate "@ manager.commanddef runflask (arg): # my_app.run () # in Django, release this item humg live print (arg) @ manager.option ("-n ","-name ", dest=" name ") @ manager.option ("-s ") "--say", dest= "say") def talk (name, say): print (f "{name} but true {say}") if _ _ name__ = ='_ main__': # my_app.run () manager.run () # replace the original my_app.run () manager.py4.2 executes the database initialization instruction python manager.py database init

At this point you will find a migrations directory in your project directory.

4.3 executing database migration instructions python manager.py database migrate # is equivalent to makemigrationpython manager.py database upgrade # in Django and migrate in Django

At this point you will notice that a users table appears in the database.

These are all the contents of the article "how to use the flask Framework". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report