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

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:123456@localhost/admin'

4. 代码

from flask import Flask

from test.db.models import User, db

app = Flask(__name__)


app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1: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')

 

发布了13 篇原创文章 · 获赞 2 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览