[英]django/python : error when get value from dictionary
我在dotcloud和redhat openshift上托管了python / django代碼。 為了處理不同的用戶,我使用令牌並將其保存在字典中。 但是當我從字典中獲取值時,有時會拋出錯誤(鍵值錯誤)。
import threading
thread_queue = {}
def download(request):
dl_val = request.POST["input1"]
client_token = str(request.POST["pagecookie"])
# save client token as keys and thread object as value in dictionary
thread_queue[client_token] = DownloadThread(dl_val,client_token)
thread_queue[client_token].start()
return render_to_response("progress.html",
{ "dl_val" : dl_val, "token" : client_token })
以下代碼通過javascript xmlhttprequest發送到服務器,每隔1秒執行一次。 它將檢查另一個線程中的變量,並將該值返回到用戶頁面。
def downloadProgress(request, token):
# sometimes i use this for check the content of dict
#resp = HttpResponse("thread_queue = "+str(thread_queue))
#return resp
prog, total = thread_queue[str(token)].getValue() # problematic line !
if prog == 0:
# prevent division by zero
return HttpResponse("0")
percent = float(prog) / float(total)
percent = round(percent*100, 2)
if percent >= 100:
try:
f_name = thread_queue[token].getFileName()[1]
except:
downloadProgress(request,token)
resp = HttpResponse('<a href="http://'+request.META['HTTP_HOST']+
'/dl/'+token+'/">'+f_name+'</a><br />')
return resp
else:
return HttpResponse(str(percent))
經過幾天的測試,有時會返回:
thread_queue = {}
有時會成功:
thread_queue = {'wFVdMDF9a2qSQCAXi7za': , 'EVukb7QdNdDgCf2ZtVSw': , 'C7pkqYRvRadTfEce5j2b': , '2xPFhR6wm9bs9BEQNfdd': }
當我通過manage.py runserver在本地運行django並使用google chrome訪問它時,我從未得到此結果,但是當我將其上傳到dotcloud或openshift時,它總是會出現上述問題。 我的問題 :
謝謝。
dotCloud默認為python服務提供4個工作進程。 在本地運行開發服務器時,僅運行一個進程。 就像@martijn所說的那樣,您的問題與以下事實有關:您的命令將不會在這些進程之間共享。
要解決此問題,您可以使用redis或memcached之類的方法來存儲此信息。 如果您需要更長期的存儲解決方案,那么使用數據庫可能更合適。
dotCloud並不限制CPU使用率,CPU在同一主機上共享,並且允許突發,但最終每個人都擁有相同數量的CPU。
查看您的代碼,您應該在訪問字典之前檢查並確保該字典中有一個值,或者至少在代碼中用try try塊包圍,以處理數據不存在的情況。
str_token = str(token)
if str_token in thread_queue:
prog, total = thread_queue[str_token].getValue() # problematic line !
else:
# value isn't there, do something else
大概dotcloud和openshift運行代碼的多個過程; dict將不會在這些進程之間共享。
請注意,這也意味着額外的進程也將無法訪問您的額外權限。
請使用外部數據庫獲取此類信息。 對於此類長期運行的異步作業,您還需要在單獨的工作進程中運行它們。 例如,請參見Celery,了解用於異步作業處理的多合一解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.