Search code examples
pythonmultithreadingflask

How to start threads in Flask without the page freezing?


I'm making a Flask app where I paste several torrent info hashes in a textarea and my app would start downloading those torrents. This is my code:

        # app.py
    content = request.form['downloads']
    info_hashes = content.strip().strip('\n').split('\n')
    threads = []
    try:
        for h in info_hashes:
            threads.append(threading.Thread(target=downloader(h)))

        for t in threads:
            t.start()

        flash('Download started.')

    except Exception as e:
        flash(str(e))





# downloader.py
from torrentp import TorrentDownloader

def downloader(info_hash):
        SAVE_PATH = '/media/zemen/HDD/jellyfin'
        torrent_file = TorrentDownloader(f"magnet:?xt=urn:btih:{info_hash}", SAVE_PATH)
        torrent_file.start_download()

So my problem is that while the downloads are happening my website just keeps loading. How do I make the downloads run in the background? Please help, thanks.


Solution

  • You are not starting the threads properly.

    threading.Thread(target=downloader(h))
    

    Here you are assigning whatever is the result (probably None in this case) of downloader(h) as the target for the thread, not the downloader function itself. In other words, you are not starting the download in a thread at all, but trying to do it beforehand instead.

    threading.Thread expects a callable + args, so you need to pass a reference to the function instead, like this:

    threading.Thread(target=downloader, args=[h])
    

    See examples in https://docs.python.org/3/library/threading.html#threading.Thread for more information.