Reload Variable Data from DB without restarting Django

Question:

I have a function in my Django Views.py and I use the data in another function but if a user changes True to False then I want to update it without having to restart Django.

def update_list():
    global processess
    processess = botactive.objects.filter(active=True).values_list('user')


update_list()

I use processess which fetches users who have a model field set to True but if they set it to False I want to not include them if there is a new request.

listi = [row[0] for row in processess] 
def wallet_verify(listi):
    # print(listi)
    database = Bybitapidatas.objects.filter(user = listi)
    ...

This is the request I make and want it to use fresh data without restarting Django and also in python and not using html.

def verifyt(request):
    with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor:
        results = executor.map(wallet_verify, listi)
    return HttpResponse("done")
    
Asked By: user18377368

||

Answers:

Ignoring the relative merits of globals in Django for the moment, you could just recreate the query in verifyt() to make sure its fresh.

def verifyt(request):
    v_processess = botactive.objects.filter(active=True).values_list('user')
    v_listi = [row[0] for row in v_processess] 
    
    with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor:
        results = executor.map(wallet_verify, v_listi)
    return HttpResponse("done")

(It might be worth noting, Django queries are lazily evaluated, so, by the looks of it, your query won’t actually be performed until listi is set anyway, which may do unpredictable things to your global.)

Another option might be to make your query into a function so you can call it when you need it and always get the latest

def get_listi():
    processess = botactive.objects.filter(active=True).values_list('user')
    listi = [row[0] for row in processess] 
    return listi


def verifyt(request):
    listi = get_listi()
    with ProcessPoolExecutor(max_workers=4, initializer=django.setup) as executor:
        results = executor.map(wallet_verify, listi)
    return HttpResponse("done")

def wallet_verify(user_from_listi):
    database = Bybitapidatas.objects.filter(user = user_from_listi)
    ...
Answered By: SamSparx
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.