我正在设置一个烧瓶应用程序来运行匿名在线实验。如何通过current_user
登录管理器的对象跟踪匿名参与者?
当用户匿名时,current_user
设置为AnonymousUserMixin
. 我试图分配AnonymousUserMixin
一个 id 变量(例如通过 uuid.uuid4() ),current_user=None
但它不再是 ORM 对象。我试图遵循这篇文章的第二个答案的建议(如何使用 Flask 跟踪匿名用户),但我缺乏如何将所描述的方式转换为实际代码的知识。
所以我最终得到了错误消息“AnonymousUserMixin”对象没有属性“_sa_instance_state”,我似乎无法解决。
关于如何current_user
与匿名用户一起使用该对象的任何建议?
这里有一些相关的代码部分[编辑:代码根据@Roch的建议进行了调整]:
模型.py
from website import db
# models for database structure
class DemographicData(db.Model):
__tablename__ = 'demographic_data'
id = db.Column(db.Integer, primary_key=True)
gender = db.Column(db.String(1), nullable=False)
age = db.Column(db.Integer, nullable=False)
nationality = db.Column(db.String(50), nullable=False)
# create relationships to the other models to link them to the demographicData
consentRequest = db.relationship('ModalData', backref='participant_bref', lazy=True)
def __repr__(self):
return f"demographicData('{self.id}', '{self.gender}', '{self.age}', '{self.nationality}')"
class ModalData(db.Model):
__tablename__ = 'modal_data'
id = db.Column(db.Integer, primary_key=True)
participantId = db.Column(db.Integer, db.ForeignKey('demographic_data.id'), nullable=False)
consent = db.Column(db.String(3), nullable=False)
def __repr__(self):
return f"modalData('{self.participantId}', '{self.consent}')"
路线.py
from flask import render_template, url_for, redirect, request, session
from website import app, db
from website.models import DemographicData, ModalData
from website.questionnaires import DemographicsForm
@app.before_request
def make_session_permanent():
session.permanent = True
# route to demographic information form
@app.route("/demographics", methods=['GET', 'POST'])
def demographics():
form = DemographicsForm()
if form.validate_on_submit():
participant = DemographicData(gender=form.gender.data,
age=form.age.data,
nationality=form.nationality.data)
session['anonymous_user_id'] = participant.id
# save to database
db.session.add(participant)
db.session.commit()
return redirect(url_for('megazine'))
return render_template('demographics.html', title='Demographic Information', form=form)
# route to a website I want to redirect to after demographics
@app.route("/megazine", methods=['GET', 'POST'])
def megazine():
if request.method == 'POST':
consentDecision = ModalData(participant_bref=session['anonymous_user_id'],
consent=request.form['consentForm'])
db.session.add(consentDecision)
db.session.commit()
return redirect(url_for('motivemag'))
return render_template('/newswebsite_templates/megazine/index.html', title='Megazine')