当前位置:网站首页>I use flask to write the website "II"
I use flask to write the website "II"
2022-06-26 06:26:00 【@Weidada (°) з °)-*】
Last one : I use Flask Write a website 《 One 》
Use Flask-SQLAlchemy Plug in management database
Write it at the front
The original plan is to introduce the use of... In detail in this article Flask The project layout needed to develop the website , That is, how different code is stored in the project , This will also help me to continue the following explanation . however , because Last one Too little content was introduced , A direct explanation of the project structure will cause the novice children's shoes to be acclimatized , So instead, let's talk about how to Flask Database plug-ins are used in the application .
This is also in line with my idea of writing this series , Problem solving oriented , natural , After the code is messy , Then systematically modify the framework of the whole project , Easy to receive , The effect may also be better .
Before studying this article , Please be sure to install Mysql.
1. Use Flask-SQLAlchemy plug-in unit
Flask It's a very lightweight ( Simple 、 Function less ) Framework , It provides rich functions through various plug-ins ,Flask-SQLAlchemy It is one of the thousands of plug-ins .
Speaking of Flask-SQLAlchemy, I have to say SQLAlchemy. Careful children's shoes may have found , There are two packets on the network , One is called sqlalchemy, The other is flask-sqlalchemy. The relationship between the two is very simple ,sqlalchemy Is aimed at Python Object relational mapping of (ORM) frame , and flask-sqlalchemy Is in the sqlalchemy On the basis of the encapsulation , Make it in Flask It is easier to apply on .
Let me give you a brief introduction ORM frame ,ORM(Object-Relational-Mapping) Refers specifically to the mapping between objects and relationships . The relation is the table in the database , Object refers to the object in object-oriented ( class ), Mapping refers to the relationship between tables and objects .
Under normal circumstances, we operate the database with SQL sentence , Used Flask-SQLAlchemy Then you can manipulate the object directly , You don't need to write anything SQL Code .
for example , Use SQL Query all users , The code is as follows :
select * from t_user;
Use sqlalchemy It only needs :
User.query.all()
The results of the two are exactly the same , therefore , choice Flask-SQLAlchemy No discussion .
I don't say much nonsense , Start immediately .
First , Get into Last one Established ahoh Folder , Then activate Python A virtual environment :
~$ cd ahoh
~/ahoh$ . venv/bin/activate
In the use of Flask-SQLAlchemy Before , You need to install the corresponding package first , as well as Mysql The driver pymysql:
(venv)~/ahoh$ pip install pymysql
(venv)~/ahoh$ pip install flask-sqlalchemy
After installation , stay ~/ahoh/app.py Introduce in the file Flask-SQLAlchemy The corresponding class :
from flask_sqlalchemy import SQLAlchemy
And then in app=Flask(__name__) Add the parameter corresponding to the configuration after the statement , And create SQLAlchemy object :
app.config.from_mapping(
SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:[email protected]/ahoh?charset=utf8',
SQLALCHEMY_TRACK_MODIFICATIONS=True
)
db= SQLAlchemy(app)
SQLALCHEMY_DATABASE_URI Configuration of variables , Just to show SQLAlchemy Indicate the type of database you are using 、 drive 、 Database user name 、 password 、IP And database name , The details are as follows: :

then , Don't forget to , stay Mysql Create the corresponding database in , What we use here is ahoh, The commands to create a database are as follows :
create database ahoh;
Come here ,Flask-SQLAlchemy The configuration of the plug-in has been completed , however , We can't test it yet .
Since it's object relational mapping (ORM) frame , Must also provide object , Then it can be mapped to relational tables .
SQLAlchemy object
So-called SQLAlchemy object , It's just a special class , It's right here app.py End of file , Additional User class :
class User(db.Model):
__tablename__ = 't_users' # The corresponding database table name
id = db.Column(db.Integer, primary_key=True, autoincrement=True) # Since the primary key
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(127), nullable=False)
Every attribute in this class , All correspond to a column of a table in the database , It should be easier to understand ,db.Integer and db.String Are the two most commonly used types ,SQLAlchemy There are many other types of data , Later, we will gradually expand our code .
To make sure everyone can keep up , The following post app.py Code for :
# ~/ahoh/app.py
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_mapping(
SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:[email protected]/ahoh?charset=utf8',
SQLALCHEMY_TRACK_MODIFICATIONS=True
)
db = SQLAlchemy(app)
@app.route('/')
def index():
return ' Hello , Flask'
... ... # The code is too long , Other view functions are omitted here
class User(db.Model):
__tablename__ = 't_users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True)
password = db.Column(db.String(127), nullable=False)
OK, Here we are. , be-all sqlalchemy The work is done , Let's start the test work .
Let's use Flask Shell Complete the creation of tables in the database , Test code correctness .
Flask Shell Create data table
use first Ctrl+C Stop the running Flask service , Then type on the command line :
(venv)~/ahoh$ flask shell # start-up Flask Shell
Python 3.8.10 (default, Nov 26 2021, 20:14:08)
[GCC 9.3.0] on linux
App: app [production]
Instance: /home/wei/ahoh/instance
>>> # A command prompt appears to indicate successful startup
Flask Shell and Python An interactive programming environment is similar , We don't delve into , Just start .
stay Shell Enter the following code in :
>>> from app import db # introduce db Variable
>>> db.create_all() # Create all tables
The above instructions , All inheritance will be created db.Model The table corresponding to the class of , If you're typing db.create_all() No output after ( No error message ), A high probability is success .
then , Open a new terminal , Get into Mysql see ahoh Whether a table is actually created in the database :
mysql> use ahoh;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+----------------+
| Tables_in_ahoh |
+----------------+
| t_users |
+----------------+
1 row in set (0.00 sec)
mysql>
You can also use DESC Instruction view table structure :
mysql> desc t_users;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| username | varchar(80) | NO | UNI | NULL | |
| email | varchar(120) | YES | UNI | NULL | |
| password | varchar(127) | NO | | NULL | |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
mysql>
The table building work is finished here , The following test data table is added, deleted, modified and checked .
go back to Flask Shell, Enter the following command , towards t_users Insert data into the table :
>>> from app import User # introduce User class
>>> u = User(username='xiaoming',email='[email protected]',password='123456') # establish User example
>>> db.session.add(u) # Add new data to the database
>>> db.session.commit() # Submit
If after executing the above instructions , No error message , It's really bad .
Hurry back to Mysql Check it out. t_users Is there any data in the table , Use the following instructions :
mysql> select * from t_users; # Query all data in the table
+----+----------+-------------+----------+
| id | username | email | password |
+----+----------+-------------+----------+
| 1 | xiaoming | [email protected] | 123456 |
+----+----------+-------------+----------+
1 row in set (0.00 sec)
The output is the same as me, which proves that there is no problem !
remind : Password plaintext storage is a very stupid behavior , This is for display only , Encryption will be used later
This is also the reason why the password column has a large reserved space , Did you find out
Only one piece of data must be outrageous , Add a few more :
>>> u1 = User(username='aaa',password='bbb',email="[email protected]")
>>> u2 = User(username='eee',password='bbb',email="[email protected]")
>>> db.session.add(u1)
>>> db.session.add(u2)
>>> db.session.commit()
Then test delete 、 Modification function :
# Delete the test
>>> u = User.query.filter_by(username='aaa').first() # Inquire about
>>> u.username
'aaa'
>>> db.session.delete(u) # Delete
>>> db.session.commit()
# Revision Test
>>> u = User.query.filter_by(username='xiaoming').first()
>>> u.username
'xiaoming'
>>> u.username=' god '
>>> db.session.add(u)
>>> db.session.commit()
Flask-Migrate Database version control
Now the database and Flask-SQLAlchemy The plug-ins are all configured , New problems are coming .
I am not satisfied with the data sheet now , Because there is no age age Field , And I hope that the final database will have many tables , There must be a big gap between now and now .
So I need to constantly revise db.Model Subclasses of , How to modify the object class every time , Synchronize changes to the database ?
This requires Flask-Migrate Plug in , First , Old rules , Installing a plug-in :
(venv) ~/ahoh$ pip install flask-migrate
The next step is configuration Flask-Migrate plug-in unit , It's simple , First in app.py File header import :
from flask_migrate import Migrate
And then in db=SQLAlchemy(app) Create after migrate example :
migrate = Migrate(app, db)
This completes the configuration .
Flask-Migrate It is also very convenient to use , There are three commands
The first is the initialization command :flask db init
In the first installation Flask-Migrate After the plug-in , It needs to be carried out once , There is no need for .
Let's initialize :
(venv) ~/ahoh$ flask db init
Creating directory /home/wei/ahoh/migrations ... done
Creating directory /home/wei/ahoh/migrations/versions ... done
Generating /home/wei/ahoh/migrations/script.py.mako ... done
Generating /home/wei/ahoh/migrations/env.py ... done
Generating /home/wei/ahoh/migrations/alembic.ini ... done
Generating /home/wei/ahoh/migrations/README ... done
Please edit configuration/connection/logging settings in '/home/wei/ahoh/migrations/alembic.ini' before
proceeding.
If your output is the same as mine , Even if it's successful .
Next, the migration command :flask db migrate
(venv) ~/ahoh$ flask db migrate
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
INFO [alembic.env] No changes in schema detected.
Finally, the upgrade command : flask db upgrade
(venv) ~/ahoh$ flask db upgrade
INFO [alembic.runtime.migration] Context impl MySQLImpl.
INFO [alembic.runtime.migration] Will assume non-transactional DDL.
Only this and nothing more ,Flask-Migrate The preparatory work for the project has been completed , Then you can modify the database .
Next :
边栏推荐
- Gof23 - builder mode
- Customer Stories | Netease spring breeze: the "spring breeze" of the fun industry, reaching out to all areas through in-depth interaction
- Underlying principle of MySQL index
- 浏览器的四大内核:Trident,Gecko,Webkit,Blink
- 消息队列-全方位对比
- Lamda expression
- How to make the main thread wait for the sub thread to execute before executing
- 01 golang and matlab code of knapsack problem
- STM 32 使用cube 生成TIM触发ADC并通过DMA传输的问题
- Go language learning notes 1.2- variables
猜你喜欢

Go语言学习笔记 1.1

How to select and build a real-time data warehouse scheme

Connexion et déconnexion TCP, détails du diagramme de migration de l'état

MYSQL索引不生效的原因

消息队列-功能、性能、运维对比
![[spark] how to implement spark SQL field blood relationship](/img/8e/96f83844b480916b2662b0cf1fdf65.jpg)
[spark] how to implement spark SQL field blood relationship

Gof23 - prototype mode
The sysdig 2022 cloud native security and usage report found that more than 75% of the running containers have serious vulnerabilities

Reasons why MySQL indexes are not effective

Comparison between Prometheus and ZABBIX
随机推荐
【golang】time相关
个人博客系统需求分析
ByteDance starts the employee's sudden wealth plan and buys back options with a large amount of money. Some people can earn up to 175%
浏览器的四大内核:Trident,Gecko,Webkit,Blink
打印数字的位信息
Installing rainbow in various kubernetes with Helm
成水最多的容器
Library management system
Custom reference formats used by Zotero
Data visualization practice: Data Visualization
Message queue - function, performance, operation and maintenance comparison
Use the fast proxy to build your own proxy pool (mom doesn't have to worry about IP being blocked anymore)
typescript的class结合接口(interface)的简单使用
Laravel 实现 groupBy 查询分组数量
消息队列-功能、性能、运维对比
TCP connection and disconnection, detailed explanation of state transition diagram
How to select and build a real-time data warehouse scheme
Efk Upgrade to clickhouse log Storage Reality
ts中枚举类型(enum)简单使用
Lamda expression