Revision cda71050 snf-cyclades-app/synnefo/plankton/utils.py

b/snf-cyclades-app/synnefo/plankton/utils.py
1
# Copyright 2011 GRNET S.A. All rights reserved.
1
# Copyright 2011-2013 GRNET S.A. All rights reserved.
2 2
#
3 3
# Redistribution and use in source and binary forms, with or
4 4
# without modification, are permitted provided that the following
......
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.
33 33

  
34
from functools import wraps
35
from synnefo.plankton.backend import ImageBackend
36 34
from contextlib import contextmanager
37

  
38
def plankton_method(func):
39
    """Decorator function for API methods using ImageBackend.
40

  
41
    Decorator function that creates and closes an ImageBackend, needed
42
    by all API methods that handle images.
43
    """
44
    @wraps(func)
45
    def wrapper(request, *args, **kwargs):
46
        with image_backend(request.user_uniq) as backend:
47
            request.backend = backend
48
            return func(request, *args, **kwargs)
49
    return wrapper
35
from synnefo.plankton import backend
36
from snf_django.lib.api import faults
50 37

  
51 38

  
52 39
@contextmanager
53 40
def image_backend(user_id):
54
    """Context manager for ImageBackend"""
55
    backend = ImageBackend(user_id)
41
    """Context manager for ImageBackend.
42

  
43
    Context manager for using ImageBackend in API methods. Handles
44
    opening and closing a connection to Pithos and converting backend
45
    erros to cloud faults.
46

  
47
    """
48
    image_backend = backend.ImageBackend(user_id)
56 49
    try:
57
        yield backend
50
        yield image_backend
51
    except backend.Forbidden:
52
        raise faults.Forbidden
53
    except backend.ImageNotFound:
54
        raise faults.ItemNotFound
58 55
    finally:
59
        backend.close()
56
        image_backend.close()

Also available in: Unified diff