#In my views.py file
pi1 = None
pis1 = None
def my_func():
#Essentially this function sets a random integer to pi1 and pis1
global pi1, pis1
pi1 = randint(0,9)
pis1 = randint(0,9)
return
def index(request):
my_func()
context = {
"pi1" : pi1,
"pis1" : pis1,
}
return render(request, "index.html", context)
#In the index.html file
<h1>{{ pi1 }}</h1>
<h1>{{ pis1 }}</h1>
I've removed a lot of my code for simplicity, but this is the gist of it. Despite the code that I've posted for my_func, it is a time consuming function that causes index.html to load for awhile when it is accessed. How would I run my_func in the backround using celery and redis so that index.html loads more quickly?
I've read the celery documentation, but I am still having trouble setting up celery and redis. Thank you.
As is said previous, you might not need celery. Here's an example derived from case 2 of this: https://zapier.com/blog/async-celery-example-why-and-how/. It's fully working for me:
My index.html contains:
And my urls.py contains:
What happens when I visit localhost:8000/test/ is that I instantly see:
After about 10 seconds, I then see:
The idea is that you return your page instantly and use jquery to fetch the result of the operation whenever that's finished and update your page accordingly. You can add more things like progress bars/loading image etc. For your example, you can do the processing for
pi1
andpis
in the background and load it into the HTML after that's finished.You don't need celery here. You can load these values on page with AJAX request. You should create a separate view that will calculate this values and after the index.html is loaded call it with javascript.