What you are looking for is readiness check. Basically readiness is a concept wherein something reports to be ready to handle requests (this something could be a web server, a docker container, a kubernetes pod, a database, etc.)
You can custom define an API endpoint that returns 200 OK when your Django server is ready to handle the requests, and internally make a request to that API endpoint and only execute your file once the endpoint returns 200 OK.
Alternatively, there are third-party packages (a quick google search revealed
django-probes) that might assist you in implementing something similar.
Logically, at a primitive level, your flow would be something along the lines of:
- Define an API endpoint:
- This should return a custom response WHILE it is YET to be ready to start taking requests
- This should return a different custom response WHEN it is ready to start taking requests
- Once you have the desired "ready" response, you go on invoking the file, until then you keep delaying it by adding a second's sleep or something.
Sample code
import requests
"""
api_endpoint is the custom endpoint that returns your desired
response based on whether or not Django Server is ready to take
on requests
"""
response = requests.get(api_endpoint)
while response.status_code != 200:
time.sleep(1) # Sleep for 1 second
response = requests.get(api_endpoint)
# Once this while loop breaks, this indicates we are good to proceed
if response.status_code == 200:
# Do rest of your job here