Exemple #1
0
def add(request_format):
    url = request.form.get('url')

    if url:
        try:
            trucks = [ImageTruck.new_from_url(url)]
        except RequestException:
            abort(request_format, 400, "That url is no good.")
    elif request.files.get('file[]'):
        trucks = [ImageTruck.new_from_stream(data.stream)
                  for data in request.files.getlist('file[]')]
    elif request.files.get('file'):
        data = request.files['file']
        trucks = [ImageTruck.new_from_stream(data.stream)]
    else:
        abort(request_format, 400, "Please submit either a file or a url.")

    # These loops are sorta awkwardly phrased to avoid lots of round-tripping
    # to the database. I hope you don't consider the optimization premature.
    session = Client().session()
    images = []
    for truck in trucks:
        image = Image(filename=truck.filename, source_url=url)
        album_id = request.form.get('album_id')
        if album_id:
            image.album_id = int(album_id)
        session.add(image)
        images.append(image)

    session.flush()
    contentses = []
    for i in xrange(0, len(images)):
        (truck, image) = trucks[i], images[i]
        contents = ImageContents(image_id=image.image_id,
                                 contents=truck.contents,
                                 content_type=truck.content_type)
        session.add(contents)
        contentses.append(contents)
    session.flush()

    task_ids = []
    # Hey, this is a loop around a round-trip to redis. Although the Python
    # Redis library offers a way to send multiple requests in one thwack,
    # Celery doesn't appear to offer a way to use it. Nothing to be done.
    for contents in contentses:
        task_ids.append(delay(g.queued_tasks,
                              process_image,
                              contents.image_contents_id))

    if request_format == 'html':
        return redirect(url_for('show_image', image_id=image.image_id))
    elif request_format == 'json':
        return [{
                'url': trucks[i].url(),
                'image_id': images[i].image_id,
                'task_id': task_ids[i],
            } for i in xrange(0, len(trucks))]
Exemple #2
0
    def wrapper(request_format, *args, **kwargs):
        if g.user is None:
            if request_format == 'html':
                return redirect('/')
            else:
                abort(request_format, 401, "You must log in to do that.")

        else:
            return fn(request_format, *args, **kwargs)
Exemple #3
0
def add(request_format):
    url = request.form.get("url")

    if url:
        try:
            trucks = [ImageTruck.new_from_url(url)]
        except RequestException:
            abort(request_format, 400, "That url is no good.")
        except TryHTTPError:
            abort(
                request_format,
                400,
                "Catsnap couldn't establish an HTTPS connection to that "
                "image. An HTTP connection may succeed (this is a problem "
                "on Catsnap's end, not something you did wrong).",
            )
    elif request.files.get("file[]"):
        trucks = [ImageTruck.new_from_stream(data.stream) for data in request.files.getlist("file[]")]
    elif request.files.get("file"):
        data = request.files["file"]
        trucks = [ImageTruck.new_from_stream(data.stream)]
    else:
        abort(request_format, 400, "Please submit either a file or a url.")

    # These loops are sorta awkwardly phrased to avoid lots of round-tripping
    # to the database. I hope you don't consider the optimization premature.
    session = Client().session()
    images = []
    for truck in trucks:
        image = Image(filename=truck.filename, source_url=url)
        album_id = request.form.get("album_id")
        if album_id:
            image.album_id = int(album_id)
        session.add(image)
        images.append(image)

    session.flush()
    contentses = []
    for i in xrange(0, len(images)):
        (truck, image) = trucks[i], images[i]
        contents = ImageContents(image_id=image.image_id, contents=truck.contents, content_type=truck.content_type)
        session.add(contents)
        contentses.append(contents)
    session.flush()

    task_ids = []
    # Hey, this is a loop around a round-trip to redis. Although the Python
    # Redis library offers a way to send multiple requests in one thwack,
    # Celery doesn't appear to offer a way to use it. Nothing to be done.
    for contents in contentses:
        task_ids.append(delay(g.queued_tasks, process_image, contents.image_contents_id))

    if request_format == "html":
        return redirect(url_for("show_image", image_id=image.image_id))
    elif request_format == "json":
        return [
            {"url": trucks[i].url(), "image_id": images[i].image_id, "task_id": task_ids[i]}
            for i in xrange(0, len(trucks))
        ]
Exemple #4
0
def edit_image(request_format, image_id):
    if request_format != 'json':
        abort(request_format, 400, "This endpoint is JSON-only...")

    session = Client().session()
    image = session.query(Image).\
        filter(Image.image_id == image_id).\
        one()

    for attribute, value in request.form.iteritems():
        if attribute in ['add_tag', 'remove_tag']:
            continue

        if hasattr(image, attribute):
            if attribute in ['album_id', 'title', 'description']:
                if not value:
                    value = None
                setattr(image, attribute, value)
            else:
                abort(request_format, 400, "'{0}' is read-only".format(attribute))
        else:
            abort(request_format, 400, "No such attribute '{0}'".format(attribute))

    if 'add_tag' in request.form:
        tag = request.form['add_tag']
        image.add_tags([tag])

    if 'remove_tag' in request.form:
        tag = request.form['remove_tag']
        image.remove_tag(tag)

    session.add(image)
    try:
        session.flush()
    except IntegrityError:
        abort(request_format, 404, "No such album_id '{0}'".format(image.album_id))

    return {
        'status': 'ok',
        'image': {
            'album_id': image.album_id,
            'title': image.title,
            'caption': image.caption(),
            'description': image.description,
            'tags': list(image.get_tags()),
        }
    }
Exemple #5
0
def edit_image(request_format, image_id):
    if request_format != "json":
        abort(request_format, 400, "This endpoint is JSON-only...")

    session = Client().session()
    image = session.query(Image).filter(Image.image_id == image_id).one()

    for attribute, value in request.form.iteritems():
        if attribute in ["add_tag", "remove_tag"]:
            continue

        if hasattr(image, attribute):
            if attribute in ["album_id", "title", "description"]:
                if not value:
                    value = None
                setattr(image, attribute, value)
            else:
                abort(request_format, 400, "'{0}' is read-only".format(attribute))
        else:
            abort(request_format, 400, "No such attribute '{0}'".format(attribute))

    if "add_tag" in request.form:
        tag = request.form["add_tag"]
        image.add_tags([tag])

    if "remove_tag" in request.form:
        tag = request.form["remove_tag"]
        image.remove_tag(tag)

    session.add(image)
    try:
        session.flush()
    except IntegrityError:
        abort(request_format, 404, "No such album_id '{0}'".format(image.album_id))

    return {
        "status": "ok",
        "image": {
            "album_id": image.album_id,
            "title": image.title,
            "caption": image.caption(),
            "description": image.description,
            "tags": list(image.get_tags()),
        },
    }
 def trigger_for_test(request_format):
     abort(request_format, 500, "No Mr. Bond, I expect you to die.")