我有两个模型,一个是包含两个 ID(first_id 和 second_id)的 Identification,第二个是 User。这个想法是只有授权用户才会获得他们的 first_id 和 second_id 值对。他们进入网站并通过输入两个 ID 以及用户名和密码(他们在那里生成)登录。
我想在这里实现两件事:
使用许多(假设 100 个)first_id/second_id 值预填充标识表,这些值将用作登录的正确值对。
以这样一种方式设置 User 类,即只有当用户在登录表单中输入正确的 first_id/second_id 对时,他们才能登录(推测这涉及以某种方式检查表单数据与 Identification 表)。
这是模型类:
class Identification(db.Model):
id = db.Column(db.Integer, primary_key=True)
first_id= db.Column(db.Text, unique=True)
second_id= db.Column(db.Text, unique=True)
def __init__(self, first_id, second_id):
self.first_id= first_id
self.second_id= second_id
def __repr__(self):
return f"ID: {self.id}, first_id: {self.first_id}, second_id: {self.second_id}"
class User(db.Model, UserMixin):
__tablename__ = 'user'
first_id= db.relationship('Identification', backref = 'identificationFID', uselist=False)
second_id = db.relationship('Identification', backref = 'identificationSID', uselist=False)
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.Text, unique=True, index=True)
password_hash = db.Column(db.Text(128))
identification_id = db.Column(db.Integer, db.ForeignKey('identification.id'), unique=True)
first_id = db.Column(db.Text, unique=True)
second_id = db.Column(db.Text, unique=True)
我很感激任何帮助,因为我正在努力,这确实超出了我对 python/Flask 的理解。谢谢大家!
最佳答案
上面的答案对我不起作用,因为 create_tables()
函数作为 User 类的一部分,要求我传递该类的实例。
我想到的解决方案是在 db.create_all()
之后调用该函数。由于 @app.before_first_request
装饰器,这似乎是一个打电话的好地方。
初始化.py
@app.before_first_request
def create_tables():
"""Create Tables and populate certain ones"""
db.create_all()
from app.models.init_defaults import init_defaults
init_defaults()
初始化默认值.py
def init_defaults():
"""Pre-Populate Role Table"""
if Role.query.first() is None:
roles = ['Admin', 'Master', 'Apprentice']
for role in roles:
user_role = Role(access_level=role)
if role != 'Apprentice':
user_role.set_password('Passw0rd!')
db.session.add(user_role)
db.session.commit()
pass
由于装饰器,该函数现在每个实例只调用一次。我可以想象的另一种解决方案是使用事件: https://dzone.com/articles/how-to-initialize-database-with-default-values-in
注意:这是一个不适合生产的开发解决方案。
关于python - 预填充 Flask SQLAlchemy 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56063458/