Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask persistent object between requests

I am creating a web interface for OMXPlayer on the Raspberry Pi. I'm trying to create a more REST like API for controlling the video while its playing. The issue I'm having is how to control the video while it is playing.

Currently I can create a Player object which as some methods available to start and stop the video.

@main.route("/video", methods=["GET", "POST"])
@login_required
def video():
    form = VideoForm()

    if form.validate_on_submit():
        url = form.url.data
        vid_output = form.vid_output.data
        player = Player(url=url, output=vid_output)
        player.toggle_pause()
        return redirect('/video')

    return render_template("video.html", form=form)

Now I want to have another URL that can run the Player.toggle_pause() method again.

@main.route("/video/stop", methods=["GET", "POST"])
@login_required
def video_stop():
    player.toggle_pause()

My problem is that I cannot find a way to have this object persist between the two requests. The video will start playing after sending the first request, but trying to stop or control it will not allow me to access the created object. Is there a way to persist this object between two seperate requests?

like image 351
Majormjr Avatar asked Mar 16 '23 18:03

Majormjr


1 Answers

The only way to preserve information across requests is to store it somewhere and retrieve it on the next request. Or recreate the object (including state) using parameters passed from the client.

For your case, since you'll only be using one Player at any given time, you can make it global. (Stripped some lines for consiseness)

player = None

def video():
    global player
    form = VideoForm()
    if form.validate_on_submit():
        url = form.url.data
        vid_output = form.vid_output.data
        player = Player(url=url, output=vid_output)

def video_pause():
    global player
    if not player:
        return
    player.toggle_pause()

def video_stop():
    global player
    if not player:
        return
    player.exit_omx_player()
    player = None
like image 140
junnytony Avatar answered Mar 24 '23 11:03

junnytony