1

With a django button, I need to launch multiples music (with random selection).

In my models.py, I have two functions 'playmusic' and 'playmusicrandom' :

def playmusic(self, music):
    if self.isStarted():
        self.stop()

    command = ("sudo /usr/bin/mplayer "+music.path)
    p = subprocess.Popen(command+str(music.path), shell=True)
    p.wait()


def playmusicrandom(request):    
    conn = sqlite3.connect(settings.DATABASES['default']['NAME'])
    cur = conn.cursor()
    cur.execute("SELECT id FROM webgui_music")
    list_id = [row[0] for row in cur.fetchall()]

    ### Get three IDs randomly from the list ###
    selected_ids = random.sample(list_id, 3)

    for i in (selected_ids):
        music = Music.objects.get(id=i)
        player.playmusic(music)

With this code, three musics are played (one after the other), but the web page is just "Loading..." during execution...
Is there a way to display the refreshed web page to the user, during the loop ?? Thanks.

Isador
  • 595
  • 3
  • 10
  • 23

1 Answers1

1

Your view is blocked from returning anything to the web server while it is waiting for playmusicrandom() to finish.

You need to arrange for playmusicrandom() to do its task after you're returned the HTTP status from the view.

This means that you likely need a thread (or similar solution).

Your view will have something like this:

import threading

t = threading.Thread(target=player_model.playmusicrandom,
                             args=request)
t.setDaemon(True)
t.start()
return HttpResponse()

This code snippet came from here, where you will find more detailed information about the issues you face and possible solutions.

Community
  • 1
  • 1
GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
  • Great ! Thank you , it works. Just, my hardware has one processor listed in `cat /proc/cpuinfo` (raspberry pi). Which of methods is more advised ? (Thread, Multiprocess, etc...). – Isador Oct 18 '14 at 13:41
  • Sorry to post an issue about this solution, it works, but my stop function stop only the current mplayer process (pkill), and I would to kill the entire thread, but I've seen that was not really possible... ? Do you have an idea ? – Isador Oct 25 '14 at 08:51