欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flask3:Mysql数据库操作(Database First)

程序员文章站 2023-12-28 11:56:46
...

1.安装插件

pipenv install flask-sqlalchemy
Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project. You can set PIPENV_IGNORE_VIRTUALENVS=1 to force pipenv to ignore that environment and create its own instead. You can set PIPENV_VERBOSITY=-1 to suppress this warning.
Installing flask-sqlalchemy…
✔ Installation Succeeded 
Installing dependencies from Pipfile.lock (5ea30a)…
  ????   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 8/8 — 00:00:05

2.安装驱动

pipenv install pymysql
Installing pymysql…
✔ Installation Succeeded 
Installing dependencies from Pipfile.lock (b0a7e7)…
  ????   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 9/9 — 00:00:04

3.配置文件中增加配置项

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]/admin'

4. 代码

from flask import Flask

from test.db.models import User, db

app = Flask(__name__)


app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:[email protected]:3306/admin?charset=utf8'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

#将应用上下文推入栈,否则无法运行
ctx = app.app_context()
ctx.push()

db.init_app(app)

user = User.query.filter_by(account = 'ljz').first()

if user:
    print(user.name)
else:
    print('not found')

 

上一篇:

下一篇: