flask 使用 sqlalchemy 访问 MySQL 数据库

更新日期: 2023-10-04 阅读次数: 546 字数: 413 分类: Python

之前用的 python orm 库 orator 发现不但很久没更新了,而且安装报错。 为了保险起见还是继续使用 sqlalchemy 吧,毕竟是主流。

flask 还有个专门的库封装了 sqlalchemy。

安装 flask sqlalchemy

pip install -U Flask-SQLAlchemy
pip install pymysql
pip install cryptography

pymysql 是一个纯 python 实现的访问 mysql 的一个库。

版本号确认

从 pip 的输出,可以看到安装的版本

Successfully installed Flask-SQLAlchemy-3.1.1 greenlet-3.0.0 sqlalchemy-2.0.21

或者通过 freeze 命令

> pip freeze

Flask-SQLAlchemy==3.1.1
PyMySQL==1.1.0
cryptography==41.0.4

更新 requirements.txt

因为 pip freeze 输出的版本格式,跟 requirements.txt 格式一致。

所以用 pip freeze 更合适,直接复制到 txt 中就行。

Flask-SQLAlchemy 的初始化

from flask import Flask, request
from flask_cors import cross_origin
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import Column, Integer, String


app = Flask(__name__)
app.config[
    "SQLALCHEMY_DATABASE_URI"
] = f"mysql+pymysql://root:password@localhost:3306/my_db?charset=utf8"


class Base(DeclarativeBase):
    pass


db = SQLAlchemy(model_class=Base)
db.init_app(app)


class Item(db.Model):
    __tablename__ = "item"
    id = Column(Integer, primary_key=True)
    user_id = Column(String)


item = Item(user_id="123")

with app.app_context():
    db.session.add(item)
    db.session.commit()

直接运行,会看到数据库中,立即新增了一条记录。

RuntimeError: Working outside of application context

我直接在 flask 全局创建一条记录时,直接报错。

参考:

https://flask.palletsprojects.com/en/2.3.x/appcontext/

If you try to access current_app, or anything that uses it, outside an application context, you’ll get this error message:

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context().

例如,不加 app_context 这行,就会报错:

with app.app_context():
    db.session.add(item)
    db.session.commit()

RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods

pip install cryptography

更多操作参考

  • 常用的增删改查操作: https://flask-sqlalchemy.palletsprojects.com/en/3.1.x/queries/

tags: flask

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式