配置文件
DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = 'karai0000'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = "{}+{}://{}:{}@{}:{}/{}?charset=utf8".format(DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT,
DATABASE)
代码
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#
# 配置参数
# class Config:
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:karai0000@127.0.0.1:3306/flask?charset=utf8',
# SQLALCHEMY_TRACK_MODIFICATIONS = True # 禁用追踪
import config
app.config.from_object(config)
# # 将 sqlAlchemy 和 app 绑定起来
db = SQLAlchemy(app=app)
# 创建 数据库模型类
class Role(db.Model):
__tablename__ = "role" # 表名
id = db.Column(db.Integer, primary_key=True) # id 字段 设置 数据类型 为integer , 设置主键
name = db.Column(db.String(16), unique=True) # name 字段 设置 数据类型 为 字符串 设置 值为 唯一的
class User(db.Model):
__tablename__ = "User"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16))
password = db.Column(db.String(128)) # 括号的数字是字符的长度
# 表的关系
# role_id = db.Column(db.Integer, db.ForeignKey('role.id')) # ForeignKey 外键
if __name__ == '__main__':
db.create_all()
user = User(name="程序员keven" , password = "123456")
db.session.add(user)
db.session.commit()
|