SoFunction
Updated on 2024-11-10

Example of flask + pymysql operating on a Mysql database

Install flask-sqlalchemy, pymysql modules

pip install flask-sqlalchemy pymysql 

### Introduction to Flask-SQLAlchemy

1. ORM: Object Relationship Mapping.

2. flask-sqlalchemy is an ORM framework.

3. Benefits of ORM: allows us to operate the database with the operation of the object is the same, very convenient. Because a table is abstracted into a class, a piece of data is abstracted into an object of the class.

4. Install `flask-sqlalchemy`: `sudo pip install flask-sqlalchemy`.

Installation of Mysql database

from  import SQLAlchemy 
from flask import Flask 
 
'''Configure the database'''
app = Flask(__name__) 
['SECRET_KEY'] ='hard to guess'
# Login here is the root user, fill in your own password, MySQL's default port is 3306, fill in the database name jianshu created before, connect to the way reference \
# /en/latest/dialects/ 
['SQLALCHEMY_DATABASE_URI']='mysql+pymysql://jianshu:[email protected]:3306/jianshu'
# Set this item to automatically commit changes in the database at the end of each request
['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
# Instantiation
db = SQLAlchemy(app)

Model Definition

'''Define the model, build the relationship'''
class Role(): 
 # Define the table name
 __tablename__ = 'roles'
 # Define column objects
 id = (, primary_key=True) 
 name = ((64), unique=True) 
 user = ('User', backref='role') 
 
 The #repr() method displays a readable string, which isn't entirely necessary, but is nice for debugging and testing.
 def __repr__(self): 
  return '<Role {}> '.format() 
 
class User(): 
 __tablename__ = 'users'
 id = (, primary_key=True) 
 username = ((64), unique=True, index=True) 
 role_id = (, ('')) 
 
 def __repr__(self): 
  return '<User {}>'.format()

guanxi

Relational databases create connections in different tables by using relationships. A relational diagram expresses a simple relationship between a user and a user's role. This role and user is a one-to-many relationship because a role can be subordinate to more than one user, while a user can only have one role.
The following model class demonstrates the one-to-many relationship expressed in.

class Role(): 
 # ... 
 users = ('User', backref='role') 
 
class User(): 
 # ... 
 role_id = (, ('')) 

#!/usr/bin/env python 
 
from exts import db 
from datetime import datetime 
 
 
class User(): 
 __tablename__ = 'user'
 id = (,primary_key=True,autoincrement=True) 
 username = ((50),nullable=False) 
 telephone = ((11),nullable=False) 
 password = ((100), nullable=False) 
 
class Questions(): 
 __tablename__ = 'questions'
 id = (,primary_key=True,autoincrement=True) 
 title = ((100),nullable=False) 
 content = (,nullable=False) 
 create_time = (,default=) 
 author_id = (,('')) 
 
 author = ('User',backref=('questions')) 
 
class Answer(): 
 __tablename__ = 'answer'
 id = (,primary_key=True,autoincrement=True) 
 content = (,nullable=False) 
 question_id = (,('')) 
 author_id = (,('')) 
 
 question = ('Questions',backref = ('answers')) 
 author = ('User',backref = ('answers'))

Flask-SQLAlchemy data addition, deletion, modification and checking:

1. Increase:

# Increase:
article1 = Article(title='aaa',content='bbb')
(article1)
# Affairs
()

2. Check:

# Check
# select * from article where ='aaa';
article1 = ( == 'aaa').first()
print 'title:%s' %
print 'content:%s' %

3. Change:

# Change:
# 1. Find the data you want to change first.
article1 = ( == 'aaa').first()
# 2. Take this data and change it where you need to change it.
= 'new title'
# 3. Doing transaction commits
()

4. Delete:

```
# Delete
# 1. Locate the data to be deleted
article1 = ( == 'bbb').first()
# 2. Delete this data
(article1)
# 3. Doing transaction commits
()
```

The above example of this flask + pymysql operation of Mysql database is all I have to share with you, I hope to be able to give you a reference, and I hope you will support me more.