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' :

class Player()
    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)


    def stop(self):
        """
        Kill mplayer process
        """
        p = subprocess.Popen("sudo killall mplayer", shell=True)
        p.communicate()

In my views, I use a Thread to call 'playmusicrandom':

def playmusicrandom(request):
player = Player()
#player.playmusicrandom()
t = threading.Thread(target=player.playmusicrandom)
t.setDaemon(True)
t.start()

return redirect('homepage')

So, when I click Play, three musics are played (one after the other). But when I click Stop, obviously, the current mplayer process is killed, and the 2nd process is played...

I've read it was not a good idea, but is there a solution in my case to stop a thread launched in views ? Thanks.

PS : I want to avoid to change stop to 'kill, sleep, kill, etc...'

Isador
  • 595
  • 3
  • 10
  • 23

1 Answers1

0

In my experience, the best way to have background process in django apps is to use celery. Take a look at http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html to see what would you need to include it in your setup.

meka
  • 11
  • 3