Flask-SocketIO/example/sessions.py

71 lines
1.7 KiB
Python
Raw Normal View History

2017-06-25 18:44:07 +00:00
from flask import Flask, render_template, session, request, jsonify
2017-06-25 22:18:59 +00:00
from flask_login import LoginManager, UserMixin, current_user, login_user, \
logout_user
2017-06-25 18:44:07 +00:00
from flask_session import Session
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem'
2017-06-25 22:18:59 +00:00
login = LoginManager(app)
2017-06-25 18:44:07 +00:00
Session(app)
socketio = SocketIO(app, manage_session=False)
2017-06-25 22:18:59 +00:00
class User(UserMixin, object):
def __init__(self, id=None):
self.id = id
@login.user_loader
def load_user(id):
return User(id)
2017-06-25 18:44:07 +00:00
@app.route('/')
def index():
return render_template('sessions.html')
@app.route('/session', methods=['GET', 'POST'])
def session_access():
if request.method == 'GET':
2017-06-25 22:18:59 +00:00
return jsonify({
'session': session.get('value', ''),
'user': current_user.id
if current_user.is_authenticated else 'anonymous'
})
data = request.get_json()
if 'session' in data:
session['value'] = data['session']
elif 'user' in data:
if data['user']:
login_user(User(data['user']))
else:
logout_user()
2017-06-25 18:44:07 +00:00
return '', 204
@socketio.on('get-session')
def get_session():
2017-06-25 22:18:59 +00:00
emit('refresh-session', {
'session': session.get('value', ''),
'user': current_user.id
if current_user.is_authenticated else 'anonymous'
})
2017-06-25 18:44:07 +00:00
@socketio.on('set-session')
2017-06-25 22:18:59 +00:00
def set_session(data):
if 'session' in data:
session['value'] = data['session']
elif 'user' in data:
if data['user'] is not None:
login_user(User(data['user']))
else:
logout_user()
if __name__ == '__main__':
socketio.run(app)