I have a Django view which runs a sub process and returns a JsonResponse back to the user:
def process_images(request, id):
log.debug("Processing images view...")
start = perf_counter()
result = subprocess.run(["ssh", "<REMOTE SERVER>", "bash", "process_images.sh"],
capture_output = True,
text = True) # Run backend processing
log.debug("Result stdout:\n" + result.stdout)
with open(f"{settings.MEDIA_ROOT}/{id}/image.json", "r") as f:
response_data = json.load(f)
time_took = perf_counter() - start
log.debug(f"View time took {time_took} seconds")
return JsonResponse(response_data, status=201)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<id>/process', views.process_images, name='process'),
path('<id>/', views.model, name='model')
]
app_name = "render"
However when I try accessing render/ID/process ONCE, I'm greeted with:
[Oct 25, 2022 07:30:13 PM] DEBUG [render.views:49] Processing images view...
[Oct 25, 2022 07:31:24 PM] DEBUG [render.views:55] Result stdout:
Backend processing...
[Oct 25, 2022 07:31:24 PM] DEBUG [render.views:61] View time took 70.49786422774196 seconds
[Oct 25, 2022 07:31:24 PM] DEBUG [render.views:49] Processing images view...
[Oct 25, 2022 07:32:16 PM] DEBUG [render.views:55] Result stdout:
Backend processing...
[Oct 25, 2022 07:32:16 PM] DEBUG [render.views:61] View time took 52.54661420173943 seconds
[Oct 25, 2022 07:32:16 PM] DEBUG [render.views:49] Processing images view...
[Oct 25, 2022 07:33:08 PM] DEBUG [render.views:55] Result stdout:
Backend processing...
[Oct 25, 2022 07:33:08 PM] DEBUG [render.views:61] View time took 51.900153297930956 seconds
before it finally returns the expected JsonResponse (showing that the view was called multiple times).
However, if I reduce the backend processing so that it is much faster, and then visit it again, I only get the following output:
[Oct 25, 2022 07:42:41 PM] DEBUG [render.views:49] Processing images view...
[Oct 25, 2022 07:42:44 PM] DEBUG [render.views:55] Result stdout:
Backend processing...
[Oct 25, 2022 07:42:44 PM] DEBUG [render.views:61] View time took 3.0603290796279907 seconds
where it is only called once (as expected), and with the appropriate JsonResponse.
Question: How can I ensure that the view is only called once despite large execution times?
- I would rather not use Celery or any other libraries/schedulers to aid with offline/asynchronous views
I looked at this question, but the only answer to it is specific to that question.