当前位置:网站首页>Basic use of flask Sqlalchemy
Basic use of flask Sqlalchemy
2022-06-29 01:15:00 【ch_ atu】
1. rely on
pip install flask-sqlalchemy
pip install flask-script
pip install flask-migrate
2. establish SQLAlchemy object
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]/sqlalchemy_test' # Bind database
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # Track changes to objects and signal without warning
db = SQLAlchemy(app)
# Code migration configuration
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)
3. Creating models
class User(db.Model):
__tablename__ = "user_account" # Database table name
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30))
fullname = db.Column(db.String(30))
sex = db.Column(db.String(30))
def __repr__(self):
return f"User(id={
self.id!r}, name={
self.name!r}, fullname={
self.fullname!r})"
class Address(db.Model):
__tablename__ = "address"
id = db.Column(db.Integer, primary_key=True)
email_address = db.Column(db.String(30), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey("user_account.id"), nullable=False) # Define foreign key constraints
# Define a relational model , It can be done by backref Take... In reverse
user = db.relationship('User', backref=db.backref('address', lazy=True), lazy=True)
def __repr__(self):
return f"Address(id={
self.id!r}, email_address={
self.email_address!r})"
3.1 Common data types
Integer、String(size)、DateTime、Float、Boolean
More data types :https://docs.sqlalchemy.org/en/14/core/type_basics.html#generic-types
3.2 db.Column Common configuration options
primary_key: If it is set to True, This column is the primary key of the table
unique: If it is set to True, Duplicate values are not allowed in this column
index: If it is set to True, Index this column , Improve query efficiency
nullable: If it is set to True, This column allows null values ; If it is set to False, Null values are not allowed in this column
default : Define default values for this column
More configuration options :https://docs.sqlalchemy.org/en/14/core/metadata.html#sqlalchemy.schema.Column
4. Perform the migration
# Create migration warehouse -- initialization
python manage.py db init
# Create migration script
python manage.py db migrate
# Update the database
python manage.py db upgrade
# Fallback database
python manage.py db downgrade Version number
Every time the database model changes , It needs to be reused migrate Command and upgrade command ( Combine in order ), After successful use, the version number will be modified .
5. Inquire about API
User.query Back to a BaseQuery object , This object supports sqlalchemy Many queries for API
5.1. Common filters
filter() : Add filter to original query , Return a new query
filter_by() : Add equivalent filter to the original query , Return a new query
limit(): Limit the number of results returned by the specified query , Return a new query
offset(): Offset the result returned by the original query , Return a new query
order_by(): Sort the original query results according to the specified conditions , Return a new query
group_by(): Group the original query results according to the specified conditions , Return a new query
5.2 Common query execution functions
all(): Returns all results of the query as a list
first(): Returns the first result of the query , If there is no result , Then return to None
first_or_404(): Returns the first result of the query , If there is no result , Then terminate the request , return 404 Error response
get() : Return the row corresponding to the specified primary key , If there is no corresponding line , Then return to None
get_or_404(): Return the row corresponding to the specified primary key , If the specified primary key is not found , Then terminate the request , return 404 Error response
count(): Number of returned query results
paginate(): Return to one Paginate object , It contains the results in the specified range
More inquiries API:https://docs.sqlalchemy.org/en/14/orm/query.html?highlight=cte#sqlalchemy.orm.Query
边栏推荐
- Different subsequence problems I
- Docker中安装Oracle数据库
- Finally understand the difference between DOM XSS and reflection XSS
- Day 7 scripts and special effects
- 【图像处理】基于matlab实现图像曲线调整系统
- What is the difference between the history and Western blotting
- Large-scale case applications to developing post-click conversion rate estimation with MTL
- What is the difference between immunohistochemistry and immunohistochemistry?
- Statistical learning method (3/22) k-nearest neighbor method
- Is it safe to open a securities account at qiniu business school in 2022?
猜你喜欢

【图像增强】基于matlab人工多重曝光融合AMEF图像去雾【含Matlab源码 1916期】

【图像处理】基于matlab实现图像曲线调整系统
![[staff] pedal mark (step on pedal ped mark | release pedal * mark | corresponding pedal command in MIDI | continuous control signal | switch control signal)](/img/2b/e358b22d62ce6d683ed93418ff39fe.jpg)
[staff] pedal mark (step on pedal ped mark | release pedal * mark | corresponding pedal command in MIDI | continuous control signal | switch control signal)

【火灾检测】基于matlab GUI森林火灾检测系统(带面板)【含Matlab源码 1921期】

企业和IT领导者对创新的误解
![[MCU club] design of GSM version of range hood based on MCU [simulation design]](/img/8c/933ebfaeec63c0d1ffe361cb2bb91a.jpg)
[MCU club] design of GSM version of range hood based on MCU [simulation design]

FSS object storage how to access the Intranet

统计学习方法(3/22)K近邻法

Seven mistakes in IT Governance and how to avoid them

Vulnerability mining | routine in password retrieval
随机推荐
Successfully solved (machine learning data segmentation problem): modulenotfounderror: no module named 'sklearn cross_ validation‘
机构加密资产产品上周流出4.23亿美元资金,创历史新高
企业和IT领导者对创新的误解
Drawing ECG curve with WPF
Statistical learning method (2/22) perceptron
如何进行数据库选型
DO280分配持久性存储
How to handle a SIGTERM - how to handle a SIGTERM
立创eda学习笔记:铺铜死区?孤岛?死铜?
Latest version of CorelDRAW technical suite2022
利用kubernetes资源锁完成自己的HA应用
Exclusive analysis | about resume and interview
Advanced Installer Architect创作工具
[RRT 3D path planning] rapid expansion of random tree UAV 3D path planning based on MATLAB [including Matlab source code phase 1914]
Check the open source projects of yyds in June!
[staff] accent mark, gradually stronger mark and gradually weaker mark
独家分析 | 关于简历和面试
【架构师(第三十八篇)】 服务端开发之本地安装最新版 MySQL 数据库
【图像增强】基于matlab人工多重曝光融合AMEF图像去雾【含Matlab源码 1916期】
Count the number of different palindrome subsequences in the string