How to run python code at the background without impacting rendering of html template?

Viewed 113

Concept that I want to achieve:

A web application that listens to user's speech at the background and do what the user wants.

What I have:

A Python - Django application with Speech Recognition enabled with the following two files.

  • speechrecognition.py (This is where speech recognition related logic is)
  • index.html

Note: speechrecognition.py goes on a loop repeatedly listening to user's input.

What I tried:

I tried calling speechrecognition.py class before rendering index.html in views.py

from SpeechRegApp.speechrecognition import SpeechRecognition

def index(request):  
    SpeechRecognition() 
    return render(request, "index.html", {})

Problem that I'm facing:

Since I'm repeatedly listening to user's input in speechrecognition.py, index.html doesn't get rendered.

How to fix this issue?

2 Answers

This totally make sense, since your code is trapped in that loop. There is a module in python called "threading"! I am not sure, but maybe that module can help you putting your SpeechRecognition() to background, while the rest of your code proceeds.

If you follow this link. It will show you how to set up background task with Django, Celery and Redis.

This will enable to to run your SpeechRecognition() in parallel with your existing code.

Example:

views.py

from SpeechRegApp.speechrecognition import SpeechRecognition

def index(request):  
    speech_recognition_task.delay()
    return render(request, "index.html", {})

celery.py

@celery.task
def file_transfer():
    SpeechRecognition()

Hope this helps.

Related