flask-sqlchemy use

Flask-sqlalchemy was used in the project. Let's summarize the usage here to prevent forgetting later and having to check the English information.
1. The first stage of using sqlalchemy:
first tell sqlalchemy the table structure by way of class, as follows:

class AlarmStatistical(db.Model):
    __bind_key__ = 'xnet_master'
    __tablename__ = 'dashboard_alarm_statistical'

    id = db.Column(db.Integer, primary_key=True)
    source = db.Column(db.String(255), index=True)
    pod = db.Column(db.String(255), index=True)
    start_time = db.Column(db.DateTime, index=True)
    count = db.Column(db.Integer)

    def __init__(self, source, pod, start_time, count):
        self.source = source
        self.pod = pod
        self.start_time = start_time
        self.count = count

    def alter(self):
        self.count += 1

bind_key , TableName is the flask in an environment variable that represents the path and database table names
Note points: primary_key have to have
and you can write a function in this class, when used to call these functions directly with data in the database
so we put the table completed, look at some of the following operation
2, select operation
using the basic method sqlalchemy select filter is carried out and filter_by
difference is, filter_by may be used in some complex expressions

f = AlarmStatistical.query.filter(AlarmStatistical.id == id).all()

.all () returns all of the qualified data, there are other ways
.first () returns the first data
.limit (n) return n data
as well as add about sorting methods, the official website to find specific api

It can also be used like this:

data = AlarmStatistical.query.filter(AlarmStatistical.id == id)
data = data.filter(AlarmStatistical.pod == pod).all()
#可以模糊查询、或者其他条件查询
#模糊查询:
query.filter(User.email.endswith('@example.com')).all()

If you have multiple uncertain conditions, you can use this

p0=[AlarmStatistical.id==id,]
p1=[AlarmStatistical.pod == pod]
data = AlarmStatistical.query.filter(and_(p0),and_(p1))
#或者这样
p = [AlarmStatistical.id==id, AlarmStatistical.pod == pod]
data = AlarmStatistical.query.filter(and_(p))

3. Insert data

p = AlarmStatistical(......) #调用class中的__init__()函数
db.session.add(p)
db.session.commit()

4, the use of the sql statement native
lot of complex queries, inconvenient implemented sqlalchemy object, you can use native sql statement directly, but have to pay attention to some sql attacks, such as sql injection attacks

db.engine.execute(sql)

5. Delete data

p = AlarmStatistical()
db.session.delete(p)
db.session.commit()

6, update data
to update the data, you must first inquiry to cover the data, then update

u=AlarmStatistical.query.first()
u.id=123  
#更新数据和变量赋值那么简单,但必须是通过查询返回的对象。
db.session.commit()

At this time, you can use the methods in the class, such as:

u=AlarmStatistical.query.first()
u.alter()  
db.session.commit()

7. Use functions in sql

#这个查询,会比较复杂,在现实使用中,完全可以使用原生的sql语句
data = (db.session.query(db.func.date_format(AlarmMessage.alarm_time, '%Y-%m-%d %H:%i').label('alarm_time'), AlarmMessage.alarm_source, AlarmMessage.pod,db.func.count('*').label('alarm_sum')).filter(AlarmMessage.alarm_time >= start_time, AlarmMessage.alarm_time <= end_time)
                .group_by(AlarmMessage.alarm_source, AlarmMessage.pod) )

Use the function in sql: db.func.function-name () .label ('name'), label refers to the name after querying and accessing, after using label, you can access data.name
query () like this The data
filter represents the select condition

For sqlalchemy, only simple one-to-one relationships, complex relationship operations, and later write and write.

Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/45032033