flask database using external storage modules,

flask operating mysql database

snake

Whether flask django frame or frame, are available through orm (Object-Relation Mapping), Chinese called object - relational mapping, the mapping is performed by the data model classes in the database table within the framework, so that the data table CRUD Zha, this data table corresponding model classes, class field in the database field corresponding to the object class corresponding to the model table a record, a data object corresponds to the corresponding field of the attribute table records

 

orm advantages:

  1. No longer perform native sql statement, additions and deletions can be changed as long as the database by the properties and the method for performing model-based search
  2. By the model-based operation to the database, you need to be replaced when the type of the database, can be configured according to the respective requirements, without modifying other code

 orm shortcomings

  1. different framework orm direct model class action is not the same, the statement orm operation between different languages ​​need to learn when to use different frameworks same language, or

  2. The use of model-based operation of the database, the nature of the underlying original method of green sql statement into packaging process model class, so with respect to the native sql statement, the operation model type have performance loss

Flask-SQLAlchemy

In the framework of the flask, no operation orm, so we need to install third-party module orm operate, install:

pip install flask-sqlalchemy -i https://pypi.douban.com/simple/

 Meanwhile, in order to connect to the database, you need to install drivers mysql flask-mysqldb, if the first installed in the first flask-mysqldb ubuntu, being given

OSError: mysql_config not found

The solution is to install via apt libmysqlclient-dev

APT-GET install libmysqlclient- sudo dev 

# then install 
pip install flask-mysqldb

 By adding profiles can connect to the database

from the Flask Import the Flask 

App = Falsk ( __name__ )
 class Config (): 
    DEBUG = True
     # data type: // login user: password @ database or IP address: port / database name? charset = encoding 
    SQLALCHEMY_DATABASE_URI = ' MySQL: // root: [email protected]: 3306 / flaskDemo charset = utf8mb4? ' 
    # dynamic tracking modify settings, if not set will only prompt warning 
    SQLALCHEMY_TRACK_MODIFICATIONS = True
     # displays the original SQL query statement 
    = SQLALCHEMY_ECHO True 

app.config.from_object (Config)

 Initialize the database

# Database initialization 
from flask_sqlalchemy Import SQLAlchemy 
db = SQLAlchemy (App)

SQLAlchemy commonly used model in the class of the field or column option to view the official website: https://www.sqlalchemy.org/

Commonly used model class field name or column options and common query method here: of lazy, did not write

 Create a model class:

class User(db.Model):
    __tablename__ = "user" #自定义表名

    id = db.Column(db.Integer, primary_key=True, comment="ID")
    name = db.Column(db.String(20), comment="用户名")
    age = db.Column(db.SmallInteger, nullable=True, comment="年龄")
    sex = db.Column(db.Boolean, default=True, comment="性别")
    birthday = db.Column(db.DateTime, nullable=True, comment=""Date of Birth)

Create a data table or delete data table, as SQLAlchemy does not provide data migration command, as shown in the program so the program can only be executed in

IF  the __name__ == ' __main__ ' :
     # create all the tables, according to the current system model corresponding to the application data table 
    # () db.create_all 
    # remove all tables 
    # db.drop_all () 

    app.run (Host = " 0.0.0.0 " , port = 8080, debug = True )

Deletions data change search

# Left of the equal sign is the interior of the User class by attribute name, attribute value on the right is a custom 
User = User (name = name, Age = Age, Sex Sex =, = Birthday BITD) 
db.session.add (User) 
db.session .commit ()
# Delete 

# to get the data you want to delete 
the User = User.query.first () 

db.session.delete (the User) 
the db.commit ()
# Change 

# to obtain the data to be modified 
User = User.query.first ()
 # modify the attribute values of 
the user.name = " zhangsan " 
db.session.delete (User) 
the db.commit ()
# Check 
# write within the filter query 
user = User.query.filter (). All ( )

To-many relationship between the database 

Because mysql is a relational database, so often there is a relationship between the table and the table, and this relationship relationship db can be used to declare a field indicates, you can set a positive query fields across tables and queries by the Anti field the query field, but will not change the property to form the corresponding database field names, then it is declared in a table after relationshiph, need foreign key to another table, the foreign key table associated with the two together, for example: in the above Add a foreign key table and a role role-based User class on

class Role (db.Model): 
    ... 
    # critical code attribute will not change table generating data corresponding field, the field is declared by field user_list forward query by reverse query by a value corresponding to backref Role 
the lazy = Dynamic Representative lazy query, that query execution statements are not true, when will use to query the data, when lazy = subquery will immediately query
user_list = db.relationship ( ' the User ' , backref = ' Role ' , lazy = ' Dynamic ' ) . .. class the User (db.Model): ... # new foreign key field role_id = db.Column (db.Integer, db.ForeignKey ( ' roles.id ' ))

 

The database-many relationship 

This relationship between two tables of data tables where a table corresponding to a plurality of data from another table, this time we need a third table to link the two tables together again

 

 

As described above, in the middle of the table may be too StuToCourse foreign key to the table together again studnent association table and course, many examples can be up by, the processing other than the foreign key, we need to set the property to control the query db.relationship student tables and course of the forward and reverse lookup queries.

Then set the third table when there are two methods for setting, in which student and course shown in the following table

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment="ID")
    name = db.Column(db.String(20), comment="用户名")
    age = db.Column(db.SmallInteger, nullable=True, comment="年龄")
    sex = db.Column(db.Boolean, default=True, comment="性别")
    birthday = db.Column(db.DateTime, nullable=True, comment="出生日期")



class Course(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment="ID")
    name = db.Column(db.String(20), comment="等级")

 

method one

Add a third table by db.talbe method, this method will add disadvantages can not add additional fields:

StuToCourse = db.Table("StuToCourse",
    db.Column('id',db.Integer, primary_key=True, comment="ID"),
    db.Column("sid",db.Integer, db.ForeignKey("student.id")),
    db.Column("cid",db.Integer, db.ForeignKey("course.id")),
    )

 

After the new third table, then as long as the course of which a student or db.relationship this attribute is added to the table, as shown below

class Course(db.Model):

        ......
        
    students = db.relationship("Student",secondary=StuToCourse,backref="courses",lazy="dynamic")
    

Method Two

You can set the same as an ordinary table a score table, so we can either associate the two tables, and you can add fields to store scores of students score

class Achievement(db.Model):
    id = db.Column(db.Integer, primary_key=True, comment="主键ID")
    db.Column('score', db.Numeric, comment="分数"),
    student_id = db.Column(db.Integer, db.ForeignKey('tb_student.id'))
    course_id = db.Column(db.Integer, db.ForeignKey('tb_course.id'))

 

But this approach to the design table, the table must be re-student and course table are written on db.relationship property

class Student(db.Model):
    """学生信息"""
    .....
    score = db.relationship('Achievement', backref='student', lazy='dynamic')

class Course(db.Model):
    """课程信息"""
    ......
    score = db.relationship('Achievement', backref='course', lazy='dynamic')

 

Database Migration

In the above we know that creating tables and databases can only be added by adding code db.create_all () and db.drop_all () method, so if the project is running, we can not add the program how to do, this time, we can data migration by third-party modules, and this third-party modules that flask-migrate, change this MigrateCommand module provides provides a database migration command

Before using this module, we need to install the module: pip install flask-migrate

Then, you need to add two configuration

# The first parameter is Flask example, the second parameter is the database instance Sqlalchemy 
the migrate = the Migrate (App, db) 

# Manager Flask-Script is an example of this statement to add a command db flask-Script in 
manager.add_command ( ' DB ' , MigrateCommand)

 

Then we can see through the python manage.py command (first enter the execution app.run before executing python manage.py () where the program files directory, a file named manage.py)

Commonly used commands are migrating

1. Initialize data migration directory
python manage.py db init

2. The database initialization data migration version of
python manage.py db migrate -m 'initial migration '

3. Upgrade version [Creating tables]
Python manage.py db upgrade

4. downgraded version [Delete table]
Python manage.py db downgrade

flask operating redis database

 In the project, the data is typically stored in mysql, but the data for the following changes frequently, we can put it in the cache, so it is necessary until the flask is how redis database CRUD operations, by the session information is stored in redis how to connect flask of operation redis

First, you need to ensure that the system has redis, installation rendsis pip install redis

Secondly, the session is stored in redis, you need to download third-party modules flask-session installation: pip install flask-session

Then add the configuration in the configuration file

from Flask Import Flask, the session
 from redis Import the Redis
 from flask_session Import the Session 

# instantiated objects Flask 
App = Flask ( the __name__ )
 class Config1:
     '' ' the session storage mode using redis ' '' 
    the DEBUG = True
     # key can base64.b64encode (os.urandom (48)) to generate a random string of specified length 
    of SECRET_KEY = ' GMncFpwL1oQ2A / xIHI0K / W0BDSTuOsx the eG + ++ bhgW4kJIKRRAYaybmy7Gkp1GTbcO ' 


    # connection parameters are redis IP, port number, database name 
    SESSION_REDIS = redis (host = "127.0.0.1 " , Port = 6379, db = 0) 
    
    # session type Redis 
    session_type = " Redis " 
    # If set to True, the failure to close the browser session. 
    SESSION_PERMANENT = False
     # whether to send to the browser's session encrypted cookie value 
    SESSION_USE_SIGNER = False
     # saved to prefix the value of the session 
    SESSION_KEY_PREFIX = " session: " 

app.config.from_object (Config) 

db.init_app (App) 
the session (App)

 

By this example we until, by Redis (host = "127.0.0.1", port = 6379, db = 0) generated by the operation of the database objects

 

 

Guess you like

Origin www.cnblogs.com/mark--ping/p/11688725.html