This is the 14th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Flask-SQLALchemy

define

Flask-sqlalchemy provides a flask-friendly wrapper for the popular SQLAlchemy package, which is designed to simplify the use of SQLAlchemy in flaskers and is an ORM. ORM allows applications to manage a database using high-level entities (such as classes, objects, methods) instead of tables and SQL, and its job is to translate high-level operations into database commands. The mapping between relational databases and Python objects is implemented, giving up some performance overhead in exchange for greater development efficiency and developer convenience.

Install Flask-SQLALchemy and connect to the database

Flask-sqlalchemy is installed directly from the PIP install flask-sqkalchemy command line.

PIP install flask-mysqldb: PIP install flask-mysqldb: PIP install flask-mysqldb: PIP install flask-mysqldb

Flask-SQLALchemy: Flask-SQLALchemy: Flask-SQLALchemy

Flask = flask (__ name __,static_url_path=’/’); ‘Database :// Login user: password@IP address: Port/database name ‘.

Related statements are as follows:

  • app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/ss_flask'
  • sqlite:////tmp/test.db
  • mysql://username:password@server/db

Config [‘SQLALCHEMY_TRACK_MODIFICATIONS’] = False Flask-SQLAlchemy will track modifications and signal them if set to True (default). This requires extra memory and can be disabled if not necessary.

After setting these parameters, instantiate the database management object: DB = SQLAlchemy(app). If no error is reported after the instantiation, it can connect to the database normally.

Operating database

Create database table

Flask-SQLAlchemy

First create a class, and then define the corresponding fields in it.

class User(db.Model) :
    __tablename__ = 'User_table'
    username = db.Column(db.String(80), unique=True)
    pw_hash = db.Column(db.String(80))
    id = db.Column(db.Integer,primary_key=True)
Copy the code

Db.create_all () : db.create_all()

Complete code:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__,static_url_path='/')
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)  # Instantiate an object

class User(db.Model) :
    __tablename__ = 'User_table'
    username = db.Column(db.String(80), unique=True)
    pw_hash = db.Column(db.String(80))
    id = db.Column(db.Integer,primary_key=True)


db.create_all()

if __name__ == '__main__':
    app.run()
Copy the code

insert

Insert: Flask – SQLAlchemy inserts data into a database, instantiates a User object, then passes it in. If there is an error, roll it back, commit it, and close the connection (db.session.close() is important, because if you do not close the connection, the database will be occupied all the time. Affects performance).

def add() :
    user = User(username='aaa',pw_hash="123".id=1)
    try:
        db.session.add(user)
    except:
        db.session.rollback()
    db.session.commit()
    db.session.close()
Copy the code

delete

The delete operation is similar to the insert operation. The specific statement is db.session.query(object name).filter(object name). Field name = a value).delete(),db.session.query() is the query statement, where filter() is the function used for filtering.

Example:

def del_user() :
    try:
        db.session.query(User).filter(User.id= =1).delete()
    except:
        db.session.rollback()
    db.session.commit()
    db.session.close()
Copy the code

conclusion

Flask: That’s the end of today’s flask tutorial, please give me a thumbs up if you like it!