flask_alchemy 连接 mysql

松成和
2023-12-01
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'liuzhiyu'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'pythonflask'

app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 防止出现警告
app.config['SQLALCHEMY_DATABASE_URI'] = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME,
                                                                                     PASSWORD, HOST, PORT,
                                                                                     DATABASE)
db = SQLAlchemy(app)


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username


db.create_all()

flask_sqlalchemy可以建表不能创建数据库,运行前需要先建立对应数据库。

 类似资料: