Python 在cookie中保存轮询
所以我有一个简单的投票应用程序,它不断地创建投票,人们可以投票+1或-1。然而,由于该网站不需要用户登录,人们可以在每次投票中多次投票Python 在cookie中保存轮询,python,session,cookies,flask,Python,Session,Cookies,Flask,所以我有一个简单的投票应用程序,它不断地创建投票,人们可以投票+1或-1。然而,由于该网站不需要用户登录,人们可以在每次投票中多次投票 <form name="poll" id='{{ item.id }}' method="post" action='/poll'> <label class='lab-pos'> <input type="radio" name="point
<form name="poll" id='{{ item.id }}' method="post" action='/poll'>
<label class='lab-pos'>
<input type="radio" name="points" id='whine-pos' value=1>
<img class='img-pos'src="/static/item-pos.png">
</label>
<label class='lab-neg'>
<input type="radio" name="points" id='whine-neg' value=-1>
<img class='img-neg'src="/static/item-neg.png">
</label>
</form>
我的观点如下
class pollingresult(db.Model):
__tablename__ = "pollingresult"
id = db.Column('id', db.Integer, primary_key=True)
poll = db.Column('poll', db.Integer)
cookie = db.Column('cookie', db.String(255))
feed_id = db.Column('feed_id', db.Integer)
def __init__(self, poll):
self.poll = poll
@app.route('/poll', methods=['GET', 'POST'])
def poll():
polltodb = pollingresult(request.form['points'])
session['points_session'] = request.form['points']
db.session.add(polltodb)
db.session.commit()
return ('',204)
我已经在会议上玩过了,但似乎在刷新投票时,投票仍在“休息”,以便人们可以再次投票
编辑161202: 因此,我仍然在努力完成这项任务,我可以将会话['points_session']保存到会话中,但我需要将会话保存得更像一个dict,其中dict的id=item.id和points=points,这样我就可以使用javascript“if id=1和point=1”对表单进行预填充,并使用id=1对表单进行预填充。我还需要防止基于会话再次提交表单,所以我想我必须为某种会话密钥创建一个虚拟令牌 编辑161207: 因此,我希望将poll_id与表单submit一起发送,这样我就可以使用ajax post请求,但是,这会引发错误“无法解码JSON对象:无法解码JSON对象”
这将与某种会话密钥一起插入数据库。不保存用户在会话中投票的投票,只需在会话中附加一个“投票用户id”,即可在数据库中跟踪用户及其投票
from uuid import uuid1 as uuid
if "poll_user_id" not in session:
session["poll_user_id"] = uuid()
这里有一些psuedo代码,因为我不熟悉Flask及其数据库引擎
old_vote = query(poll_user_id=session["poll_user_id"], poll=poll_id)
if not old_vote:
insert(poll_user_id=session["poll_user_id"], poll=poll_id, choice=form.choice)
else:
update(poll_user_id=session["poll_user_id"], poll=poll_id, choice=form.choice)
现在,当用户投票时,无论是新的还是作为更新,它都会检查是否已经存在具有相同“poll\u user\u id”值的投票,如果已经存在,您将进行更新。如果它不做插入操作。我建议您根本不要使用cookies。我使用浏览器指纹识别用户。这样做的好处是,即使他们一次又一次以匿名方式打开页面,您也可以识别他们(这将清除您的所有cookie/会话) 您最好生成一个(公认是半唯一的)指纹,并以这种方式跟踪重复用户的指纹。
我已经很成功地使用了它,我有一个链接,用户可以在其中标记他没有完成投票/操作,我没有true,但我仍然必须将
poll\u id
与poll\u user\u id
一起放入数据库。但是现在,您可以将这两个选项(用户和投票)关联起来,并且只在他们再次投票时更新他们的选择,而不是进入新行。您也不需要保留他们在会议中投票的所有投票。
@app.route('/poll', methods=['GET', 'POST'])
def poll():
polltodb = pollingresult(request.form['points'])
session['points_session'] = request.form['points']
db.session.add(polltodb)
db.session.commit()
data = request.get_json(force=True)
print data
return ('',204)
from uuid import uuid1 as uuid
if "poll_user_id" not in session:
session["poll_user_id"] = uuid()
old_vote = query(poll_user_id=session["poll_user_id"], poll=poll_id)
if not old_vote:
insert(poll_user_id=session["poll_user_id"], poll=poll_id, choice=form.choice)
else:
update(poll_user_id=session["poll_user_id"], poll=poll_id, choice=form.choice)