3

我正在尝试在 Django 中实现一个进度条,我正在从这个代码片段中获取参考,我发现http://djangosnippets.org/snippets/2898/但我的努力正在失败,因为我不知道发生了什么,但是执行方法任务时,task_idfor celery 始终为空,这是我的代码:

def add_categoria(request):
        if request.POST:
            form_cat = CategoriaModelForm(request.POST,request.FILES)
            if form_cat.is_valid():
                file = request.FILES['imagen']
                job = upload_image_categoria(request).delay()
                request.session['task_id'] = job.id
                return HttpResponse(json.dumps({'task_id':job.id}))
            else:
                return HttpResponseBadRequest(json.dumps(form_cat.errors),
                                            mimetype="application/json")
        else:
             form = CategoriaModelForm()
             return render_to_response("ventas/form.html",{'form':form},context_instance=RequestContext(request))


@task()
def upload_image_categoria(request):
        form = CategoriaModelForm(request.POST, request.FILES)
        path = MEDIA_ROOT+'/categorias/%s' % form.cleaned_data['imagen'].name
        file = request.FILES['imagen']
        destination = open(path, 'wb+')
        porcentaje = 0
        acum = 0
        for chunk in file.chunks():
            time.sleep(0.1)
            current_task.update_state(state='PROGRESS', meta={'current': porcentaje})
            acum += len(chunk)
            porcentaje = int((acum*100)/file.size)
            destination.write(chunk)

@csrf_exempt
def upload_state(request):
       """ A view to report the progress to the user """
       data = 'Fail'
       if request.is_ajax():
           if 'task_id' in request.POST.keys() and request.POST['task_id']:
               task_id = request.POST['task_id']
               task = AsyncResult(task_id)
               data = task.result or task.state
           else:
               data = 'No task id'
       else:
           data = 'This is not an ajax request'
       json_data = json.dumps(data)
       return HttpResponse(json_data, mimetype='application/json')

所以,当我总是报告进度条的状态时,upload_image_categoriacurrent_task.update_state(state='PROGRESS', meta={'current': porcentaje})会得到这个 Traceback:

Traceback:
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      115.                         response = callback(request, *callback_args, **callback_kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
      25.                 return view_func(request, *args, **kwargs)
    File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in add_categoria
      446.             job = upload_image_categoria(request).delay()
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in __call__
      330.             return self.run(*args, **kwargs)
    File "/Users/Tone/Documents/Proyectos/dgp/ventas/forms.py" in upload_image_categoria
      462.         current_task.update_state(state='PROGRESS',meta={'current': i, 'total': 100})
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/app/task.py" in update_state
      695.         self.backend.store_result(task_id, meta, state)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/base.py" in store_result
      282.         self._store_result(task_id, result, status, traceback, **kwargs)
    File "/Users/Tone/blog-env/lib/python2.7/site-packages/celery/backends/amqp.py" in _store_result
      128.                             routing_key=task_id.replace('-', ''),

    Exception Type: AttributeError at /ventas/categorias/add/
    Exception Value: 'NoneType' object has no attribute 'replace'

那是我的 celery 选项的 settings.py:

    BROKER_URL = "amqp://guest@localhost:5672//"
    CELERY_IMPORTS = ("ventas.forms",)
    CELERY_TRACK_STARTED = True
    CELERY_RESULT_BACKEND = "amqp"
    CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'
    CELERY_RESULT_DBURI = "mysql://root@localhost/dgp"

所以我不知道发生了什么,工人是正确的,设置(我猜,是正确的)而且我总是得到相同的,我在其他一些具有相同设置的项目中证明(这个项目特别是http://iambusychangingtheworld.blogspot。 com.es/2013/07/django-celery-display-progress-bar-of.html),它工作得很好,所以我不知道为什么不在这里,我错过了什么?任何想法将不胜感激。

问候!

4

0 回答 0