Основная цель этого вопроса состоит в том, чтобы узнать, как обновить кэш из базы данных (которая заполняется какой-то другой командой, не находящейся под нашим контролем) в службе отдыха django, которая затем будет использоваться при обслуживании запросов, полученных в конечной точке отдыха. В настоящее время я использую следующий подход, но меня беспокоит то, что python (cpython с GIL) не является многопоточным, тогда мы можем иметь следующий тип кода в службе отдыха, где один поток заполняет кэш каждые 30 минут, а основной поток обслуживает запросы на конце концаточка. Вот пример кода только для иллюстрации.
# mainproject.__init__.py
globaldict = {} # cache
class MyThread(Thread):
def __init__(self, event):
Thread.__init__(self)
self.stopped = event
def run(self):
while not self.stopped.wait(1800):
refershcachefromdb() # function that takes around 5-6 mins for refreshing cache (global datastructure) from db
refershcachefromdb() # this is explicitly called to initially populate cache
thread = MyThread(stop_flag)
thread.start() # started thread that will refresh cache every 30 mins
# views.py
import mainproject
@api_view(['GET'])
def get_data(request):
str_param = request.GET.get('paramid')
if str_param:
try:
paramids = [int(x) for x in str_param.split(",")]
except ValueError:
return JsonResponse({'Error': 'This rest end point only accept comma seperated integers'}, status=422)
# using global cache to get records
output_dct_lst = [mainproject.globaldict[paramid] for paramid in paramids if paramid in mainproject.globaldict]
if not output_dct_lst:
return JsonResponse({'Error': 'Data not available'}, status=422)
else:
return JsonResponse(output_dct_lst, status=200, safe=False)