Flask-SQLAlchemy and SQL Alchemy difference, contact

Recently we look at the project, but also sqlalchemy, there flask_sqlalchemy, some uses both almost confused. Summarize here.


A, SQL Alchemy

SQL Alchemy is the most famous python ORM (Object Relationship Mapping) framework. ORM: Object-relational mapping. Python class database table associated with the upcoming user-defined, and these classes (objects) corresponding to the instance table rows associated.


Basic Operation 1. SQL Alchemy

1.1 database connection

from sqlalchemy import create_engine

# 创建数据库引擎
engine = create_engine("mysql+pymysql://root:[email protected]:3306/my_db?charset=utf8mb4")

create_engine () function in the sense of the string, the database + Database Connectivity Framework: // username: password @IP address: port number / name of the database connection parameters?.

Explanation:

Mysql database connection, pymysql Frame connection (of course there are other connection frame), the user login and password database root and 123456, when mysql database system address 127.0.0.1:3306, the specific database connection is my_db, and provided the character encoding is utf8mb4.

1.2 Statement mapping (modeling database tables)

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

# 声明性基类
Base = declarative_base()

# 构建数据库表的模型类
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)

    # 这个是可选的方法,这里自定义在显示User对象时的格式
    def __repr__(self):
        return "<User(name='%s', fullname='%s', nickname='%s')>" % (
                             self.name, self.fullname, self.nickname)

Explanation:

Declarative system using the mapping class is defined according to the base class, the base class catalog class and maintaining the table relative to the base class - this is called a base class declarative. Our application is usually only one instance of this foundation in a common module. We use declarative_base () function to create a base class.

__tablename__ variable declaration in the name of this class when creating a table based on the table.

Now we have a class "Base", according to which we can define any number of mapping class. According to the above we define it a users table, the table contains a field id, name, fullname

1.3 create an instance of the class map


user1 = User(name='ed', fullname='Ed Jones')
user2 = User(name='ed2', fullname='Ed2 Jones2')

1.4 Create Session

Above we create a connection to the database engine, where the engine needs to create a session, back to interact with the database through the session.


Session = sessionmaker(engine)
db_session = Session()

1.5 deletions change search a single table of

from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from Model import User

# 通常我们把数据库表模型统一放到一个模块里,所以这里需要导入

# 准备工作
engine = create_engine("mysql+pymysql://root:[email protected]:3306/SQLAlchemy_Pro?charset=utf8mb4")

Session = sessionmaker(engine)
db_session = Session()

# 1. 增加数据add(创建表结构的类名(字段名=添加的数据))
db_session.add(User(name="ZWQ", fullname="ZWQ zzzzz"))  # 相当于建立一条添加数据的sql语句
db_session.commit()  # 执行

# 批量添加
user1 = User(name='ed', fullname='Ed Jones')
user2 = User(name='ed2', fullname='Ed2 Jones2')
db_session.add_all([user1, user2])
db_session.commit()


# 2.查询 query(表结构的类名)
res = db_session.query(User)
print(res)  # 直接翻译输出对应的SQL查询语句

res = db_session.query(User).all()  # 返回表中所有数据对象
print(res)


for u in res:
    print(u.id, u.name, u.fullname)

res = db_session.query(Users).first()  # 取第一个,返回是对象
print(res.id, res.name)

res = db_session.query(User).filter(Users.id == 3).first()  # 返回符合条件查询结果
print(res.name)

res = db_session.query(User).filter(User.id <= 2, User.name == "ZWQ").all() # filter中的条件可以是模糊条件,多个条件
for u in res:
    print(u.id,u.name)

# 3.更改数据 update({k:v})
res = db_session.query(Users).filter(Users.id == 1).update({"name":"DragonFire"})
print(res)
db_session.commit()

res = db_session.query(User).update({"name":"ZWQ"})  # 全部修改,返回修改的数据个数
print(res)
db_session.commit()

# 4.删除 delete()结合查询条件删除
res = db_session.query(User).filter(User.id == 1).delete()  # 删除否合条件的数据,返回删除数量
print(res)
db_session.commit()

res = db_session.query(User).delete()  # 删除表中所有数据,返回删除数量
print(res)
db_session.commit()

# 关闭session
db_session.close()

Rollback: If we pass db_session.add () does not care to add information go wrong, you can use de_session.rollback () rollback operation.

2. SQL Alchemy of the (many) (many to many)

Reference article:

https://blog.csdn.net/tianpingxian/article/details/82720442

Saw a good article, I do not write themselves. When a good reference. This article has many, many-to-one-way-many (I am a bit ignorant), bi-many, and their inquiries, etc., in great detail.


二、Flask-SQLAlchemy

Flask-SQLAlchemy is an increase SQLAlchemy support for your Flask application extensions. It requires SQLAlchemy 0.6 or higher version. It is committed to simplify the use SQLAlchemy with Flask, providing useful defaults and additional assistants to complete common tasks more easily.


1. Flask-SQLAlchemy Basic Operation

1.1 A simple example:


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 实例化SQLAlchemy
db = SQLAlchemy()
# PS : 实例化SQLAlchemy的代码必须要在引入蓝图之前

app = Flask(__name__)

# 配置数据库连接
app.config[”SQLALCHEMY_DATABASE_URI“] = “mysql+pymysql://root:[email protected]:3306/SQLAlchemy_Pro?charset=utf8mb4”

# 初始化SQLAlchemy , 本质就是将以上的配置读取出来
db.init_app(app)

# 一个简单的模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

# 根据模型在数据库中生成相应的表
db.create_all()

1.2 Simple CRUD

# 导入模型
from your_application import User


# 创建数据
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')


# 写入到数据库表中
db.session.add(admin)
db.session.add(guest)
db.session.commit()

# 查询
users = User.query.all()
# [<User u'admin'>, <User u'guest'>]

admin = User.query.filter_by(username='admin').first()
# <User u'admin'>

2. Flask-SQLAlchemy of (many) (many)

2.1-to-many (one-to-many) relationship


class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

db.relationship () function returns a new property can do many things. In this case, we have to point to the Address class and load multiple addresses. How does it know that will return more than one address? Because SQLALchemy guess a useful default value from your statement. If you want to-one relationship, you can pass the uselist = False relationship ().

backref is an easy way to declare a new property in the Address class. You can also use my_address.person to get people (person) to use the address (address) of. lazy decided SQLAlchemy when it loads the data values from the database are:

  • 'Select' :( default value) that is a standard SQLAlchemy will use a select statement to load the data if necessary.
  • 'Joined': tell SQLAlchemy using the JOIN statement as a parent in the same query to load relationship.
  • 'Subquery': similar 'joined', but SQLAlchemy will use sub-queries.
  • 'Dynamic': these data are not directly loaded, SQLAlchemy returns a query object, before the data is loaded, you can filter (extract) them.

See detailed usage: (Flask - SQLalchemy the lazy attribute) [https://www.jianshu.com/p/8427da16729a]

Reverse reference (backrefs) defined in an inert (the lazy) Status: Use backref () function:


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref=db.backref('person', lazy='joined'), lazy='dynamic')

2.2-many (many-to-many) relationship

If you want to use-many relationship, you need to define an auxiliary table for a relationship. For this auxiliary table, it is strongly recommended not to use models rather than an actual table:


# 辅助表
post_tag = db.Table('post_tag',
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)

# 文章模型
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable = False)
    # 假如拿到了一个标签Tag,怎么拿到标签下的所有文章呢.反向引用Article这时用backref
    tags = db.relationship('Tag', secondary=post_tag, backref=db.backref('posts', lazy='dynamic'))

# 标签模型
class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable = False)

Other operations:


article1 = Post(title = 'aaa')
article2 = Article(title = 'bbb')
tag1 = Tag(name = '111')
tag2 = Tag(name = '222')

#实现多对多关系,一个post有两个标签
article1.tags.append(tag1)
article1.tags.append(tag2)
article2.tags.append(tag1)
article2.tags.append(tag2)

# 增加
db.session.add(article1)
db.session.add(article2)
db.session.add(tag1)
db.session.add(tag2)

db.session.commit()

# 查询
article1 = Post.query.filter(Post.title == 'aaa').first()

tags = article1.tags
for tag in tags:
    print(tag.name)

Guess you like

Origin www.cnblogs.com/ChangAn223/p/11272532.html