简体   繁体   English

Python Flask - 如何通过cookie / session记住匿名用户?

[英]Python Flask - how to remember anonymous users via cookie/session?

I`m building a Flask web site that is a part of a research experiment. 我正在构建一个Flask网站,它是研究实验的一部分。 I need to be able to remember anonymous users so every visitor to my web site will be anonymous and unique but also be remembered so they could not enter the web site again (they will get redirection to a "thank you for your participation" page). 我需要能够记住匿名用户,因此我的网站的每个访问者都将是匿名且独特的,但也会被记住,因此他们无法再次进入该网站(他们将重定向到“谢谢您的参与”页面) 。

How can I do it? 我该怎么做? I looked into flask.session (how to generate unique anonymous id and save it to user cookie?) and Flask-login (have to be with user login to get an id) but didn't find the specific solution for this problem. 我查看了flask.session(如何生成唯一的匿名id并将其保存到用户cookie?)和Flask-login(必须与用户登录才能获得id)但是没有找到针对此问题的特定解决方案。

please help. 请帮忙。

There is no perfect solution to your problem because you will not be able to identify a user if they are anonymous. 您的问题没有完美的解决方案,因为如果用户是匿名的,您将无法识别用户。

The most practical is probably to use sessions and save that they completed the survey in a session variable. 最实际的可能是使用会话并保存他们在会话变量中完成调查。 But if they clear their cookies they will be able to enter the site again. 但如果他们清除了他们的cookie,他们将能够再次进入该网站。

Example implementation: 示例实现:

from flask import session, app

@app.before_request
def make_session_permanent():
    session.permanent = True

In your survey form view: 在您的调查表格视图中:

if not "already_participated" in session:
    ... Display form

And then in your submit view: 然后在您的提交视图中:

session["already_participated"] = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM