Database preservation of flask introductory tutorial

When a computer operates data, it generally processes the data in the memory, but the memory space of the computer is limited, and when the server operates a large amount of data, it is easy to cause insufficient memory, and once the computer is turned off, the memory data will be lost. So we need to store the data.

Persistence means saving data to a storage device (such as a disk) that can be stored permanently. The main application of persistence is to store in-memory data in a relational database. Of course, it can also be stored in a disk file, an XML data file, and the like.

When we have learned mysql and oracle, we use sql commands to operate the database to add, delete, modify and check data. For developers, they can call third-party library functions or methods, and send commands to the database engine to achieve database addition, deletion, modification and query operations. For example, the pymysql library is a third-party library specially used to operate on the mysql database. pymysql The operation can see this blog: the use of pymysql .

In fact, when developers perform database operations, there is another concept: ORM.
ORM: Object Relational Mapping, Object Relational Mapping. The function is to make a mapping between the relational database and the object, so that when the database is actually operated, there is no need to deal with complex SQL statements, as long as it is operated like an object. The simple understanding is: each row of data in the database is an object.

SQLAlchemy is the most famous ORM framework in python; in Flask, Flask-SQLAlchemy is generally used to operate the database.

SQLAIchemy

Flask-SQLAlchemy installation command: pip install flask-sqlalchemy
Official documentation: https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/

First, let's take a look at a quick start example given by the official:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 创建SQLAlchemy对象
db = SQLAlchemy()
# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库URI信息
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///project.db"
# 初始化Flask对象中的数据库信息,即Flask对象与QLAlchemy()进行绑定
db.init_app(app)

From the example, we can see that using flask_sqlalchemy in Flask is divided into the following steps:

  • Step 1: Create the SQLAlchemy object
  • Step 2: Create the Flask Object
  • Step 3: In the Flask object, configure the database URI information
  • Step 4: Initialize the database information in the Flask object
  • Step 5: Use SQLAlchemy objects to operate on the database

The database information configuration in step 3 is very important, which is equivalent to including operations such as database connection and shutdown. We need to configure database connection information and other content. The list of commonly used configurations is as follows:

configuration key illustrate
SQLALCHEMY_DATABASE_URI used to connect to the database
SQLALCHEMY_BINDS Configuration for multiple database connections
SQLALCHEMY_TRACK_MODIFICATIONS Track Object Modifications

Some configurations such as SQLALCHEMY_ENGINE_OPTIONS, SQLALCHEMY_ECHO, SQLALCHEMY_RECORD_QUERIES, SQLALCHEMY_COMMIT_ON_TEARDOWN are rarely used (haven’t tried it, try again later), so I won’t write it.
Other configuration keys such as SQLALCHEMY_NATIVE_UNICODE, SQLALCHEMY_POOL_SIZE, SQLALCHEMY_POOL_TIMEOUT, SQLALCHEMY_POOL_RECYCLE, SQLALCHEMY_MAX_OVERFLOW and other configuration keys were removed in version 3.0 of flask_sqlalchemy, so I won’t introduce them here.

Configuration instructions for SQLALCHEMY_DATABASE_URI:
format:dialect+driver://username:password@host:port/database

  • dialect: Indicates the database type, such as sqlite, mysql
  • driver: Indicates the database engine and driver, such as the python script library pymysql
  • username: username to connect to the database
  • password: the password to connect to the database
  • host: IP address where the database is located
  • port: database listening port
  • database: database name

Example:
- connect to sqlite: sqlite:///path where the database db file is located
- connect to mysql: mysql+pymysql://root:[email protected]:3306/library name

Principle: sqlalchemy actually modifies the database through a certain driver, which is configured by dialect and driver, as shown in the figure:
insert image description here

table operation

method illustrate
create_all() Create a table based on the inherited Model class, if the table name already exists, neither create nor change
drop_all() Delete the corresponding table according to the class of the inherited Model

Regarding the mapping of classes and tables:

  • Class name is equivalent to table name
    • If you want to customize the table name, define the attribute in the class:__tablename__ = 自定义的表名
    • Python is generally a class name named in camel case, and the table name is converted to an underscore connection according to the class name. For example, the table name created by class UserInfo is user_info
  • In the type, through 属性名 = db.Column()the method to map to the fields in the table
    • If the first parameter in Column() defaults to the field name, the string type, if not the string type, the field name defaults to the attribute name
    • Commonly used field types are: String, Integer, Float, Double, Boolean, DateTime, Text, etc. You can find the supported data types in the \Lib\site-packages\sqlalchemy\sql\sqltypes.py file in the python installation directory , official website description: Declaring Models
    • primary_key: Whether it is the primary key, when set to True, it means that the field is the primary key. The primary key cannot be empty by default and is self-incrementing
    • Unique: Whether it is unique, when it is True, it means that the field value is unique and not repeated
    • nullable: whether it can be null, if it is True, it can be null
    • autoincrement: Whether to increase by itself, when it is True, it means that the field is increased by itself
    • default: default value

Note: db is a SQLAlchemy object

Example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/test?charset=utf8"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# 初始化Flask对象中的数据库信息
# db = SQLAlchemy(app)
db = SQLAlchemy()
db.init_app(app)

class UserInfo(db.Model):
    id = db.Column("user_id", db.Integer, primary_key=True)
    name = db.Column(db.String(50))

class SubjectManagement(db.Model):
    __tablename__ = "subject_info"
    subject_name = db.Column(db.String(25))
    subject_id = db.Column(db.Integer, primary_key=True)

if __name__ == "__main__":
    # 根据官网指示,需要在app_context()下进行表的创建和删除
    with app.app_context():
        # 创建表
        db.create_all()
        # 删除表
        # db.drop_all()

insert image description here

Table data manipulation

method describe
db.session.add(class object) Add a single piece of data
db.session.add_all(instances) Add multiple pieces of data at once. Instances are generally lists, tuples and other types of data
db.session.commit() Submit the data (if there is a modification to the database, it needs to be submitted to take effect in the database, and it is temporarily stored in the temporary storage area before commit
db.session.close() Close the session (remember to close the session, otherwise too many temporary storage areas will take up memory space)
class.query.filter_by(property name=value).filter_by(property name=value).xxx filter_by means to filter according to conditions, and multiple conditions require multiple filter_by methods (note: it is based on the attribute name instead of the field name, and the bottom layer will recognize the attribute name as the field name)
class.query.filter_by(property name=value).first() Get the first data of the query result and return the object of the class
class.query.filter_by(property name=value).all() Get all the data of the query result and return a list, the elements in the list are objects of the class
db.session.delete(res) Delete the specified data (res is the data returned by the query) (requires commit)
类.query.filter_by(id=4).delete() Delete data according to given conditions (requires commit)
class.property-name = value After querying the object of the corresponding class from the database, modify the object properties, and after committing, it will become a modification of the table data (requires commit)
class.query.filter_by(property name=value).update(data) Modify the data according to the given query conditions. The data to be modified is a dictionary, and the data is modified according to the key-value pair (requires commit)

Note: db is a SQLAlchemy object

adding data

Example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/test?charset=utf8"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy()
db.init_app(app)

class Person(db.Model):
    id = db.Column("user_id", db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(1))

if __name__ == "__main__":
    with app.app_context():
        p1 = Person(id=1, name="张三", gender="男")
        p2 = Person(id=2, name="李四", gender="女")
        p3 = Person(id=3, name="王五", gender="男")
        db.session.add(p1)
        db.session.add_all((p2, p3))
        db.session.commit()
        db.session.close()

Execute the script and query the database data, the results are as follows:
insert image description here

Query data

Example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, create_engine

# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/test?charset=utf8"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy()
db.init_app(app)

class Person(db.Model):
    id = db.Column("user_id", db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(1))

if __name__ == "__main__":
    with app.app_context():
        res1 = Person.query.filter_by(gender="男").first()
        print("---------------first()---------------")
        print("数据类型:", type(res1))
        print(res1.id, res1.name, res1.gender)

        res2 = Person.query.filter_by(gender="男").all()
        print("\n---------------all()---------------")
        print(f"数据类型:{
      
      type(res2)},元素类型:{
      
      type(res2[0])}")
        print(res2)
        for r in res2:
            print(r.id, r.name, r.gender)

        res3 = Person.query.filter_by(gender="男").filter_by(id=3).all()
        print("\n---------------多个过滤条件---------------")
        print(f"数据类型:{
      
      type(res3)},元素类型:{
      
      type(res3[0])}")
        print(res3)
        for r in res3:
            print(r.id, r.name, r.gender)

The content of the database is:
insert image description here
the execution result is:

---------------first()---------------
数据类型: <class '__main__.Person'>
1 张三 男

---------------all()---------------
数据类型:<class 'list'>,元素类型:<class '__main__.Person'>
[<Person 1>, <Person 3>, <Person 4>]
1 张三 男
3 王五 男
4 弓长张 男

---------------多个过滤条件---------------
数据类型:<class 'list'>,元素类型:<class '__main__.Person'>
[<Person 3>]
3 王五 男

change the data

Example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, create_engine

# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/test?charset=utf8"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy()
db.init_app(app)

class Person(db.Model):
    id = db.Column("user_id", db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(1))

if __name__ == "__main__":
    with app.app_context():
        # 方式一:查询数据,修改数据对象的属性,提交session
        res = Person.query.filter_by(id=2).first()
        res.name = "力士"
        db.session.commit()
        db.session.close()

        # 方式二:给定查询条件并直接update操作,提交session
        res = Person.query.filter_by(id=4)
        res.update({
    
    "gender": "女", "name": "章双双"})
        db.session.commit()
        db.session.close()

insert image description here

delete data

Example:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, create_engine

# 创建Flask对象
app = Flask(__name__)
# 在Flask对象中,配置数据库信息
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:[email protected]:3306/test?charset=utf8"
# app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy()
db.init_app(app)

class Person(db.Model):
    id = db.Column("user_id", db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    gender = db.Column(db.String(1))

if __name__ == "__main__":
    with app.app_context():
        # 方式一:查询数据并删除,提交session
        res = Person.query.filter_by(id=2).first()
        db.session.delete(res)
        db.session.commit()
        db.session.close()

        # 方式二:给定查询条件直接delete(),提交session
        res = Person.query.filter_by(id=4)
        res.delete()
        db.session.commit()
        db.session.close()

Results of the:
insert image description here

Advantages and disadvantages of ORM

From the above study, we can understand:
Advantages:

  • Data access details are hidden
  • ORM makes it very simple for us to construct solidified data results

shortcoming:

  • The performance is degraded, and the associated operation is added, and the performance will be degraded in seconds
  • Unable to solve particularly complex database operations

Guess you like

Origin blog.csdn.net/wenxiaoba/article/details/128115268