pythonDjango从函数向会话添加变量,并在同一时间从另一个视图函数访问它

2024-09-30 14:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图添加会话变量,但当第一个函数仍在运行时,另一个函数无法访问它,示例如下

def index(request):
   request.session['logs'] = []  #I define the new variable here in session
  return render(request,"index.html")

def assigntoken(request):
   #I got list of users from post request to assign token to each of them I call a class called AssignToken
    v = AssignToken() 
    #AssignToken class has attribute called log_lst I assign it to session
    request.session['log'] = v.log_lst #by making v global I can access it from another function while it still running, but request.session['logs'] is still empty until function finish, why?
    v.start(users)  #this will start loop in users list to assign tokens
    return redirect('/result')

def result(request):
    #while assigntoken function still running I should be able to access /result to see live logs but when I try to access request.session['logs'] I found it empty, it only has data after assigntoken finish running
    context = {'logs':request.session['logs']}
    return render(request,"results.html",context)

Tags: tologreturnaccessrequestsessiondefit
1条回答
网友
1楼 · 发布于 2024-09-30 14:28:59

会话在视图完成后saved by ^{}。因此,当请求仍在处理时,您将看不到您的更改。在

相反,您可以尝试使用request.session.save()在视图中手动保存会话。在

相关问题 更多 >