flask数据库
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
db = SQLAlchemy(app)
|
||||
migrate = Migrate(app, db)
|
||||
|
||||
|
||||
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)
|
||||
gender = db.Column(db.String(10)) # 新增的性别列,可以为空
|
||||
ew_gender = db.Column(db.String(10)) # 新增的性别列,可以为空
|
||||
|
||||
def __repr__(self):
|
||||
return f'<User {self.username}>'
|
||||
|
||||
|
||||
# 初始化数据库并添加数据
|
||||
def init_db():
|
||||
with app.app_context():
|
||||
# 创建所有表
|
||||
db.create_all()
|
||||
|
||||
# 检查是否已有数据,避免重复添加
|
||||
if not User.query.first():
|
||||
# 添加初始用户数据
|
||||
users = [
|
||||
User(username='john_doe', email='john@example.com'),
|
||||
User(username='jane_smith', email='jane@example.com'),
|
||||
User(username='bob_johnson', email='bob@example.com')
|
||||
]
|
||||
|
||||
db.session.add_all(users)
|
||||
db.session.commit()
|
||||
print("初始数据已添加")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
init_db()
|
||||
print("数据库已初始化")
|
||||
|
||||
migrate = Migrate(app, db)
|
||||
Reference in New Issue
Block a user