How to avoid using global variables? (Python – Flask-Socketio application)
I’m trying to figure out how to not use global variables in my app, but I can’t think of anything else.
I actually wrote a web interface with the help of the Flask-SocketIO module for real-time interaction with the music player.
Here is a piece of code for me with the play function (I guess I just need an example and then I can use it for all the other features):
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
isPlaying = False #This is the variable that I would like to avoid making global
@socketio.on('request_play')
def cycle_play():
global isPlaying
if isPlaying == True:
socketio.emit('pause', broadcast=True)
isPlaying = False
else:
socketio.emit('play', broadcast=True)
isPlaying = True
if __name__ == '__main__':
socketio.run(app, port=5001)
It’s just a stripped-down version of the code, but I think it’s enough to understand what I’m trying to accomplish.
I also need to
access the variable from other functions, and I need to do the same for the song name, duration, and current time.
Thank you in advance for your help, and please forgive me if my English is not clear.
Here is the solution I used :
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
class Player():
def __init__(self):
self.isPlaying = False
def cycle_play(self):
if self.isPlaying == True:
socketio.emit('pause', broadcast=True)
self.isPlaying = False
else:
socketio.emit('play', broadcast=True)
self.isPlaying = True
if __name__ == '__main__':
player = Player()
socketio.on('request_play')(player.cycle_play) #this is the decorator
socketio.run(app, port=5001)
Solution
You can use the user session to store such values. You can read more about the session object here: flask.pocoo.org/docs/0.12/quickstart/#sessions.
from flask import session
@socketio.on('initialize')
def initialize(isPlaying):
session['isPlaying'] = isPlaying
@socketio.on('request_play')
def cycle_play():
# Note, it's good practice to use 'is' instead of '==' when comparing against builtin constants.
# PEP8 recommended way is to check for trueness rather than the value True, so you'd want to first assert that this variable can only be Boolean.
assert type(session['isPlaying']) is bool
if session['isPlaying']:
socketio.emit('pause', broadcast=True)
session['isPlaying'] = False
else:
socketio.emit('play', broadcast=True)
session['isPlaying'] = True