How do I get an http endpoint to return a response after 1 second and run a 10 second long process (thread)?
I tried with threading without success, see details below. I thought about making the worker thread a second http endpoint and call it with an asynchronous request, but requests-futures
is not available, and it doesn’t sound kosher.
Here is the description of my use case and some details with my experiments.
I need to create an http endpoint that responds to something like this (I wouldn’t put the parameters on the url, but that’s another story):
requests.get('[...]/lockfile/filename/username')
And does something like:
- Check on the database if
filename
is already locked by another user and… - If the file is already locked respond
ERROR: file locked by <username>
- if the file is not locked:
- Start a slow background thread that creates thumbnails, etc.
- Respond
OK
immediately, before the background thread has finished
I have played a little with background threads in Anvil, but I was disappointed by two things:
- The background threads have no access to the database
- The background threads are killed as soon as the main thread returns (even if they are not
daemon
)
Here is the test app: https://anvil.works/ide#clone:IPYCU6ABQVG3OZMO=ZPYQWV3T373T3YDVZ2SXXVEJ
Here is how to test it:
import requests
requests.get('<app-url>/test/1/2/print')
requests.get('<app-url>/test/2/1/print')
requests.get('<app-url>/test/1/2/db')
requests.get('<app-url>/test/2/1/db')
After running this test the Log
table shows only rows created on the main thread, not the ones created on the worker thread, while the app log shows rows printed by both main and worker threads, but it doesn’t show the calls of the worker thread when it takes longer than the main.