Flask基础学习2

时间:2024-02-15 22:19:32

连接mysql数据库测试(专业版)

[注意1:要导入text库,否则可能出现找不到select 1错误]

[注意2:若出现下列问题,可按照模板代码的顺序db = SQLAlchemy(app) 的位置]

RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)

# MySQL所在主机名,默认127.0.0.1
HOSTNAME = "127.0.0.1"
PORT = 3306
USERNAME = "root"
PASSWORD = "****"
DATABASE = "***"
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8"

db = SQLAlchemy(app)

with app.app_context():
    with db.engine.connect() as conn:
        result = conn.execute(text("select 1"))
        print(result.fetchone())  # (1,)

ORM的实现

class User(db.Model):
    __tablename = 'admin'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    sname = db.Column(db.String(100),nullable=False)
    snumber = db.Column(db.String(100),nullable=False)
    address = db.Column(db.String(100),nullable=False)


with app.app_context():
    db.create_all()

命令行的实现及结果

mysql> show tables;
+---------------+
| Tables_in_flk |
+---------------+
| admin         |
| user          |
+---------------+
2 rows in set (0.00 sec)

mysql> desc admin;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int          | NO   | PRI | NULL    | auto_increment |
| sname   | varchar(100) | NO   |     | NULL    |                |
| snumber | varchar(100) | NO   |     | NULL    |                |
| address | varchar(100) | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

 ORM插入实现

user = User(sname='pass', snumber=10, address='163@qq.com')
db.session.add(user)
db.session.commit()
mysql> select * from admin;
+----+-------+---------+------------+
| id | sname | snumber | address    |
+----+-------+---------+------------+
|  1 | pass  | 10      | 163@qq.com |
+----+-------+---------+------------+
1 row in set (0.00 sec)

 ORM查询实现

user  = User.query.get(1)
print(user.sname)
# 输出 pass

ORM筛选实现

user  = User.query.filter_by(sname='pass')
print(user[0].address)
# 输出 163@qq.com

ORM更新实现

user  = User.query.filter_by(sname='pass').first()
user.address = '666@qq.com'
db.session.commit()

 ORM删除实现

user  = User.query.get(1)
db.session.delete(user)
db.session.commit()

ORM的单向数据绑定案例

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    sname = db.Column(db.String(100),nullable=False)
    snumber = db.Column(db.String(100),nullable=False)
    address = db.Column(db.String(100),nullable=False)
    # author = db.relationship('Article', back_populates='author')  
    # relationship 引用外键所指向的Model


class Article(db.Model):
    __tablename__= 'article'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(200),nullable=False)
    content = db.Column(db.Text,nullable=False)
    author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
    # author = db.relationship('User',back_populates='articles') 
    # relationship 引用外键所指向的Model
    author = db.relationship('User',backref='articles') # relationship 引用外键所指向的Model
    # back_populates  实现外键的信息双向绑定 ,backref 实现单向绑定

@app.route('/article/add')
def add():
    article1 = Article(title='Flask',content='xxx')
    article1.author=User.query.get(1)
    article2 = Article(title='Django',content='yyy')
    article2.author=User.query.get(1)
    db.session.add_all([article1,article2])
    db.session.commit()
    return 'ok'

@app.route('/article/find')
def find():
    user =  User.query.get(1)
    # print(user)
    for article in user.articles:
        print(article)
        print(article.title)
    return 'ok'

运行结果:

mysql> select * from article;
+----+--------+---------+-----------+
| id | title  | content | author_id |
+----+--------+---------+-----------+
|  1 | Flask  | xxx     |      NULL |
|  2 | Django | yyy     |      NULL |
+----+--------+---------+-----------+
2 rows in set (0.00 sec)

127.0.0.1 - - [13/Feb/2024 18:00:20] "GET /article/find HTTP/1.1" 200 -
Flask
Django

生成ORM模型的迁移

flask db init

flask db migrate

flask db upgrade

蓝图使用

from flask import Blueprint
bp=Blueprint('auth',__name__,url_prefix='/auth')

@bp.route('/login')
def login():
    pass

app.register_blueprint(bp)  # 注册绑定