This article mainly describes how to use the flask to manipulate the database.
The database saves the program data according to certain rules, and the program initiates the query to retrieve the required data. Web programs are most commonly based on relational model databases, which are also called SQL data because they use structured query statements. In recent years, however, document databases and key values have become a popular alternative to databases, both of which are called NoSQL databases.
Most database engines have Python packages, including open source and business packages. Flask does not restrict what type of database packages you use, so you can choose to use MySQL, Postgres, Sqlite,redis, MongoDB, or couchdb to your liking.
If none of this satisfies the requirements, there are some database abstraction layer code packages to choose from, such as SQLAlchemy and Mongoengine. Instead of working with database entities such as tables, documents, or query languages, you can use these abstract packages to work directly with high-level Python objects.
When choosing a framework, you don't necessarily have to choose a framework that already integrates flask, but choosing these frameworks can save you time writing your integration code. With the flask-Integrated Framework to simplify configuration and operation, extensions developed specifically for flask are your first choice.
For the database framework that you chose to use, select Flask-sqlalchemy.
0. Installing Flask-sqlalchemy
install flask-sqlalchemy
1. Configure Flask-sqlalchemy
In Flask-sqlalchemy, the database is specified using a URL.
Mysql:mysql://username:[email protected]/database
Postgres:postgresql://username:[email protected]/database
Sqlite:sqlite:////absolute/path/to/database
In these URLs, hostname represents the host on which the MySQL service resides, either a local host (localhost) or a remote server. Multiple databases can be hosted on the database server, so database represents the name of the databases to use. If the database requires authentication, username and password represent the user name and password for the database.
The SQLite database does not require a server, so you do not have to specify hostname, username, and password. The database in the URL is the file name of the file on your hard disk.
The database URL used by the program must be saved to the Sqlalchemy_database_uri key of the Flask configuration object. There is also a useful option in the configuration object, the Sqlalchemy_on_reardown key, which, when set to True, automatically commits changes in the database after each request is completed.
We use the SQLite database with the following configuration code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os
baseDir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config[‘SQLALCHEMY_DATABASE_URI‘] =\
‘sqlite:////‘ + os.path.join(baseDir,‘data.sqlite‘)
app.config[‘SQLALCHEMY_COMMIT_ON_TEARDOWN‘] = True
db = SQLAlchemy(app)
2. Defining the Model
Define a user table users and a role table roles, with the following code:
class User(db.Model):
__tablename__ = ‘users‘
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(64),unique=True,index=True)
def __repr__(self):
return ‘<User %r>‘ % self.username
class Role(db.Model):
__tablename__ = ‘roles‘
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
def __repr__(self):
return ‘<Role %r>‘ % self.name
Explained below:
0. Two classes of user and role inherit from Db.model
1. __tablename__
used to specify the table name
2.db. The column function specifies the type of field in the database, whether it is a primary key (Primary_key), whether it is unique (unique), indexed (index), and others such as: whether it can be empty (nullable=true), default
3. Relationship
Using a relational database, do not specify how the relationship can be done. We do not specify a relationship in the definition model, a user has a role, a role can belong to multiple users, a typical one-to-many relationship, how to define relationships in Flask-sqlalchemy?
On the code:
class User(db.Model):
__tablename__ = ‘users‘
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(64),unique=True,index=True)
role_id = db.Column(db.Integer,db.ForeignKey(‘roles.id‘))
def __repr__(self):
return ‘<User %r>‘ % self.username
class Role(db.Model):
__tablename__ = ‘roles‘
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(64),unique=True)
users = db.relationship(‘User‘,backref=‘role‘)
def __repr__(self):
return ‘<Role %r>‘ % self.name
Added two lines of code:
The first line, in the user class:
role_id = db.Column(db.Integer,db.ForeignKey(‘roles.id‘))
This sentence is better understood, and similar to the above common variables, is the user class added a role_id variable, data type db. Integer, the second parameter specifies which ID of the table the foreign key is in.
The second line, in the role class:
users = db.Relationship(‘User‘,backref=‘role‘)
This sentence is more complicated, read the following words carefully:
0. The users attribute added to the role model represents the object-oriented perspective of the relationship. For an instance of a role class, its Users property returns a list of the users associated with the role.
1. The db.Relationship()
first parameter indicates which model (class) The other end of the relationship is. If the model class has not yet been defined, it can be specified in string form.
2. The db.Relationship()
second parameter, Backref, adds a role attribute to the user class, which defines the inverse relationship. This property replaces the ROLE_ID access role model, when you get the model object instead of the foreign key value.
The above relationship is the representation of a one-to-many relationship.
Call DB. Relationship () You need to set the UserList parameter to False. As follows:
db.Relationship(‘User‘,backref=‘role‘,uselist=False)
As for the many-to-many relationship, it will be introduced slowly.
4. Database operations
Database operation, some basic: database, table creation or deletion, data deletion and modification.
0. Creating databases and Tables
db.create_all()
The Users and roles tables mentioned above are created.
1. Deleting a database
db.drop_all()
1. Insert Row
- Role_admin = Role (name=' admin ')
- User_tom = User (username=' Tom ', Role=role_admin)
- User_jim = User (username=' Jim ', Role=role_admin)
- User_tim = User (username=' Tim ', Role=role_admin)
- User_sam = User (username=' Sam ', Role=role_admin)
- Db.session.add (Role_admin)
- Db.session.add (User_tom)
- Db.session.add (User_jim)
- Db.session.commit ()
Through database session management changes made to the database, in Flask-sqlalchemy, the session is db.session
represented, before the formation is ready to write to the database, you need to add it to the session. Writing to the database requires calling the db.session.commit()
method.
2. Modify the row
We will change the Role_admin variable name to admin to administrator.
- Role_admin.name=' Administrator '
- Db.session.add (Role_admin)
- Db.session.commit ()
3. Delete rows
Delete Jim User
db.session.delete(user_jim)
db.session.commit()
4. Query lines
Query All Users
#返回结果:[<User ‘tom‘>, <User ‘tim‘>, <User ‘sam‘>]
Flask--relationship