pkosel pkosel - 1 year ago 132
Python Question

Celery task in Flask for uploading and resizing images and storing it to Amazon S3

I'm trying to create a celery task for uploading and resizing an image before storing it to Amazon S3. But it doesn't work as expected. Without the task everything is working fine. This is the code so far:


Traceback (most recent call last):
File "../myVE/lib/python2.7/site-packages/kombu/", line 579, in _receive_callback
decoded = None if on_m else message.decode()
File "../myVE/lib/python2.7/site-packages/kombu/transport/", line 147, in decode
self.content_encoding, accept=self.accept)
File "../myVE/lib/python2.7/site-packages/kombu/", line 187, in decode
return decode(data)
File "../myVE/lib/python2.7/site-packages/kombu/", line 74, in pickle_loads
return load(BytesIO(s))
File "../myVE/lib/python2.7/site-packages/werkzeug/", line 2595, in __getattr__
return getattr(, name)
File "../myVE/lib/python2.7/site-packages/werkzeug/", line 2595, in __getattr__
return getattr(, name)
RuntimeError: maximum recursion depth exceeded while calling a Python object

from PIL import Image

from flask import Blueprint, redirect, render_template, request, url_for

from myapplication.forms import UploadForm
from myapplication.tasks import upload_task

main = Blueprint('main', __name__)

@main.route('/upload', methods=['GET', 'POST'])
def upload():
form = UploadForm()
if form.validate_on_submit():
return redirect(url_for('main.index'))
return render_template('upload.html', form=form)

from StringIO import StringIO

from flask import current_app

from myapplication.extensions import celery, db
from myapplication.helpers import resize, s3_upload
from myapplication.models import MyObject

def upload_task(title, description, source):
stream = StringIO()
target = resize(source, current_app.config['SIZE']), 'JPEG', quality=95)
obj = MyObject(title=title, description=description, url=s3_upload(stream))

Thank you

Answer Source

It looks like you are attempting to pass the entire uploaded file as part of the Celery message. I imagine that is causing you some trouble. I would recommend seeing if you can save the file to the web server as part of the view, then have the message (the "delay" argument) contain the filename rather than entire file's data. The task can then read the file in from the hard drive, upload to s3, then delete it locally.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download