我正在设置一个烧瓶应用程序来运行一个匿名的在线实验。如何通过登录管理器的current_user
对象跟踪匿名参与者?
当用户匿名时,current_user
设置为AnonymousUserMixin
。我试图为AnonymousUserMixin
分配一个id变量(例如,通过uuid.uuid4()),使其不具有current_user=None
,但是它不再是ORM对象。我试图遵循本文第二个答案的建议(How to track anonymous users with Flask),但我缺乏如何将所描述的方式转换为实际代码的知识。
所以我最终收到了错误消息“ AnonymousUserMixin”对象没有属性“ _sa_instance_state”,但我似乎无法解决该问题。
关于如何与匿名用户一起使用current_user
对象的任何建议?
这里有一些相关的代码部分[ EDIT :代码已根据@Roch的建议进行了调整]:
models.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}')"
routes.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')
答案 0 :(得分:1)
您要在会话期间或会话之后跟踪用户吗?
如果您需要在匿名用户使用应用程序期间保留一些数据,则可以轻松使用Flask会话:http://flask.pocoo.org/docs/1.0/api/#flask.session
from flask import session
@app.route('/my_url1')
def my_view1():
data = None
if session.new:
# ... do something like save data in the session
session['foo'] = 'bar'
# ... do something like read data in the session
data = session['foo']
return render_template('/my_template.html', data=data)
如果您希望在会话结束后保留用户的数据,我认为合乎逻辑的事情是立即创建一个用户并对其进行登录。
from flask import session
from models import User
@app.route('/my_url1')
def my_view1():
data = None
if session.new:
user = User()
session['anonymous_user_id'] = user.id
else:
user = User.query.get(session['anonymous_user_id'])
# ... do whatever you like