python - Django / python : error when get value from dictionary

标签 python django dictionary dotcloud openshift

我在 dotcloud 和 redhat openshift 上托管了 python/django 代码。为了处理不同的用户,我使用 token 并将其保存在字典中。但是当我从字典中获取值时,它有时会抛出错误(键值错误)。

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 和 openshift 是否限制了它们的 python cpu 使用?
  • 还是python字典里面的问题?

谢谢。

最佳答案

dotCloud 默认为 python 服务有 4 个工作进程。当您在本地运行开发服务器时,您只运行一个进程。正如@martijn 所说,您的问题与您的字典不会在这些进程之间共享这一事实有关。

要解决此问题,您可以使用诸如 redis 或 memcached 之类的东西来存储此信息。如果您需要更长期的存储解决方案,那么使用数据库可能更适合。

dotCloud 不限制 CPU 使用率,CPU 在同一主机上与其他人共享,并允许突发,但最终每个人的 CPU 数量相同。

查看您的代码,您应该在访问它之前检查以确保字典中有一个值,或者至少用一个 try except block 包围代码,以处理数据不存在的情况.

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 

关于python - Django / python : error when get value from dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12003721/

相关文章:

python - 在python 2.7中同时多次运行脚本

django - Django 中的灵活分页

c++ - 在快速删除方面,C++ vector 有什么替代方案?

python - 元类可以有方法吗?

Python父类访问子类的类变量

python - Pandas:如何根据列表从数据框中删除行?

django - 多对多关系的Django管理表单

python - 无法在异步调用的函数中放入 Python 调试器?

python - 使用生成器表达式加载选项字典

python - 在 Python 中定义单词