Python烧瓶,如何避免会话共享

时间:2017-11-21 07:56:28

标签: python session flask

我有一个通过Flask托管的聊天机器人网络应用程序,通过flask_login您可以登录并使用该应用程序。但由于某种原因,如果我在不同的Web浏览器上以不同的用户身份登录,则不同的用户都在同一个会话中。这意味着如果用户X询问问题并且机器人回答,用户Y可以跟进另一个问题并继续与最初由用户X启动的机器人进行对话。如何为每个用户分配一个单独的会话?值得一提的是我在使用flask_login时没有将每个用户保存在数据库中。这是我的代码:

from flask import Flask, request, jsonify, session, redirect, url_for, g, flash
from flask_login import login_required, login_user, logout_user, LoginManager, UserMixin, current_user

import sys
import bot
import logging
import uuid

app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = str(uuid.uuid4())
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////'
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.session_protection = "strong"
class User(UserMixin):
    def __init__(self, id):
        self.id = id



@login_manager.user_loader
def load_user(user_id):
    return User(user_id)

#
# Do not change this variable in this project.  This access token is for a bot that
# has been made for this template.
#

# make a random UUID for the SESSION_ID
SESSION_ID = str(uuid.uuid4())

chat_bot = bot.Bot(CLIENT_ACCESS_TOKEN)
try:
    chat_bot.initialize()
except Exception:
    print("Something went wrong when initializing the chatbot.")
    sys.exit(1)




@app.route('/', methods=['GET', 'POST'])
def login():
    #TODO first check if user is in session
    print("bruker:" + str(g.user))
    if g.user:
        return redirect(url_for('chat_template'))
    else:
        if request.method == 'POST':
            # TODO add password verification, current passes only if password is '1'
            if request.form['password'] == '1':
                session['user'] = request.form['username']
                return redirect(url_for('chat_template'))
            else:
                #TODO handle wrong password
                flash('Invalid credentials')
        return app.send_static_file("login.html")


@app.route("/logout")
@login_required
def logout():
    print("kommer til logout")
    session.pop('user', None)
    return redirect(url_for("login"))

@app.route('/chat_template', methods=['GET', 'POST'])
@login_required
def chat_template():
    print("chat_temp:" + str(g.user))
    if g.user:
        print("g.user finnes")
        if request.method == 'POST':
            message = request.values.get('message', None)
            result = chat_bot.handle_message(message, {})
            return jsonify(result)
        else:
            return app.send_static_file("chat_template.html")
    else:
        return redirect(url_for("login"))


@app.before_request
def before_request():
    if 'user' in session:
        print("logger inn")
        g.user = SESSION_ID
        login_user(User(SESSION_ID))
    else:
        print("logged out")
        g.user = None
        logout_user()

@app.before_first_request
def before_first_request():
    g.user = None
    if 'user' in session:
        print("setter g.user")
        g.user = session['user']

@app.errorhandler(500)
def server_error(e):
    logging.exception('An error occurred during a request.')
    return """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(e), 500


if __name__ == '__main__':

    app.run(host='127.0.0.1', port=8080, debug=True)

0 个答案:

没有答案