Пример #1
0
def zip_download_url(tag, **options):
  cloudinary_params = sign_request({
    "timestamp": now(), 
    "tag": tag,
    "transformation": generate_transformation_string(**options)[0] 
  }, options)

  return cloudinary_api_url("download_tag.zip", **options) + "?" + urlencode(cloudinary_params)
Пример #2
0
def zip_download_url(tag, **options):
  cloudinary_params = sign_request({
    "timestamp": now(), 
    "tag": tag,
    "transformation": generate_transformation_string(**options)[0] 
  }, options)

  return cloudinary_api_url("download_tag.zip", **options) + "?" + urlencode(cloudinary_params)
Пример #3
0
def call_api(method, uri, params, **options):
    prefix = options.pop(
        "upload_prefix",
        cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name: raise Exception("Must supply cloud_name")
    api_key = options.pop("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.pop("api_secret", cloudinary.config().api_secret)
    if not cloud_name: raise Exception("Must supply api_secret")

    data = to_bytes(urlencode(params))
    api_url = "/".join([prefix, "v1_1", cloud_name] + uri)
    request = urllib2.Request(api_url, data)
    # Add authentication
    byte_value = to_bytes('%s:%s' % (api_key, api_secret))
    encoded_value = base64.encodebytes(
        byte_value) if PY3 else base64.encodestring(byte_value)
    base64string = to_string(encoded_value).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_header("User-Agent", cloudinary.USER_AGENT)
    request.get_method = lambda: method.upper()

    kw = {}
    if 'timeout' in options:
        kw['timeout'] = options['timeout']
    try:
        response = urllib2.urlopen(request, **kw)
        body = response.read()
    except HTTPError:
        e = sys.exc_info()[1]
        exception_class = EXCEPTION_CODES.get(e.code)
        if exception_class:
            response = e
            body = response.read()
        else:
            raise GeneralError(
                "Server returned unexpected status code - %d - %s" %
                (e.code, e.read()))
    except socket.error:
        e = sys.exc_info()[1]
        raise GeneralError("Socket Error: %s" % (str(e)))

    try:
        body = to_string(body)
        result = json.loads(body)
    except Exception:
        # Error is parsing json
        e = sys.exc_info()[1]
        raise GeneralError(
            "Error parsing server response (%d) - %s. Got - %s" %
            (response.code, body, e))

    if "error" in result:
        exception_class = exception_class or Exception
        raise exception_class(result["error"]["message"])

    return Response(result, response)
Пример #4
0
def private_download_url(public_id, format, **options):
  cloudinary_params = sign_request({
    "timestamp": now(), 
    "public_id": public_id, 
    "format": format, 
    "type": options.get("type"),
    "attachment": options.get("attachment"),
    "expires_at": options.get("expires_at")
  }, options)

  return cloudinary_api_url("download", **options) + "?" + urlencode(cloudinary_params)
Пример #5
0
def private_download_url(public_id, format, **options):
  cloudinary_params = sign_request({
    "timestamp": now(), 
    "public_id": public_id, 
    "format": format, 
    "type": options.get("type"),
    "attachment": options.get("attachment"),
    "expires_at": options.get("expires_at")
  }, options)

  return cloudinary_api_url("download", **options) + "?" + urlencode(cloudinary_params)
Пример #6
0
def call_api(method, uri, params, **options):
    prefix = options.pop("upload_prefix", cloudinary.config().upload_prefix) or "https://api.cloudinary.com"
    cloud_name = options.pop("cloud_name", cloudinary.config().cloud_name)
    if not cloud_name: raise Exception("Must supply cloud_name")
    api_key = options.pop("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.pop("api_secret", cloudinary.config().api_secret)
    if not cloud_name: raise Exception("Must supply api_secret")

    data = to_bytes(urlencode(params))
    api_url = "/".join([prefix, "v1_1", cloud_name] + uri)
    request = urllib2.Request(api_url, data)
    # Add authentication
    byte_value = to_bytes('%s:%s' % (api_key, api_secret))
    encoded_value = base64.encodebytes(byte_value) if PY3 else base64.encodestring(byte_value)
    base64string = to_string(encoded_value).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_header("User-Agent", cloudinary.USER_AGENT)
    request.get_method = lambda: method.upper()

    kw = {}
    if 'timeout' in options:
        kw['timeout'] = options['timeout']
    try:
        response = urllib2.urlopen(request, **kw)
        body = response.read()
    except socket.error:
        e = sys.exc_info()[1]
        raise GeneralError("Socket Error: %s" % (str(e)))
    except urllib2.HTTPError:
        e = sys.exc_info()[1]
        exception_class = EXCEPTION_CODES.get(e.code)
        if exception_class:
            response = e
            body = response.read()
        else:
            raise GeneralError("Server returned unexpected status code - %d - %s" % (e.code, e.read()))

    try:
        body = to_string(body)
        result = json.loads(body)
    except Exception:
        # Error is parsing json
        e = sys.exc_info()[1]
        raise GeneralError("Error parsing server response (%d) - %s. Got - %s" % (response.code, body, e))

    if "error" in result:
        exception_class = exception_class or Exception
        raise exception_class(result["error"]["message"])

    return Response(result, response)
Пример #7
0
def call_api(action, params, http_headers={}, return_error=False, unsigned=False, file=None, timeout=None, **options):
    try:
        file_io = None
        if unsigned:
          params = utils.cleanup_params(params)
        else:
          params = utils.sign_request(params, options)
    
        param_list = []
        for k, v in params.items():
            if isinstance(v, list):          
                for vv in v:
                  param_list.append((k+"[]", vv))
            elif v:
                param_list.append((k, v))            
    
        api_url = utils.cloudinary_api_url(action, **options)
    
        global _initialized
        if not _initialized:
            _initialized = True
            # Register the streaming http handlers with urllib2
            register_openers()
    
        datagen, headers = multipart_encode({})
        if file:
            if not isinstance(file, string_types):
                datagen, headers = multipart_encode({'file': file})
            elif not re.match(r'ftp:|https?:|s3:|data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$', file):
                file_io = open(file, "rb")
                datagen, headers = multipart_encode({'file': file_io})
            else:
                param_list.append(("file", file))

        if _is_gae():
            # Might not be needed in the future but for now this is needed in GAE
            datagen = "".join(datagen)

        request = urllib2.Request(api_url + "?" + urlencode(param_list), datagen, headers)
        request.add_header("User-Agent", cloudinary.get_user_agent())
        for k, v in http_headers.items():
            request.add_header(k, v)
    
        kw = {}
        if timeout is not None:
            kw['timeout'] = timeout

        code = 200
        try:
            response = urllib2.urlopen(request, **kw).read()
        except HTTPError:
            e = sys.exc_info()[1]
            if not e.code in [200, 400, 500]:
                raise Error("Server returned unexpected status code - %d - %s" % (e.code, e.read()))
            code = e.code
            response = e.read()
        except urllib2.URLError:
            e = sys.exc_info()[1]
            raise Error("Error - %s" % str(e))
        except socket.error:
            e = sys.exc_info()[1]
            raise Error("Socket error: %s" % str(e))
    
        try:
            result = json.loads(to_string(response))
        except Exception:
            e = sys.exc_info()[1]
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s", code, response, e)
    
        if "error" in result:
            if return_error:
                result["error"]["http_code"] = code
            else:
                raise Error(result["error"]["message"])
    
        return result
    finally:
        if file_io: file_io.close()    
Пример #8
0
def download_archive_url(**options):
    params = options.copy()
    params.update(mode = "download")
    cloudinary_params = sign_request(archive_params(**params), options)
    return cloudinary_api_url("generate_archive") + "?" + urlencode(bracketize_seq(cloudinary_params), True)
Пример #9
0
def call_api(action, params, **options):
    try:
        file_io = None
        return_error = options.get("return_error")
        if options.get("unsigned"):
          params = utils.cleanup_params(params)
        else:
          params = utils.sign_request(params, options)
    
        param_list = []
        for k, v in params.items():
            if isinstance(v, list):          
                for vv in v:
                  param_list.append((k+"[]", vv))
            elif v:
                param_list.append((k, v))            
    
        api_url = utils.cloudinary_api_url(action, **options)
    
        global _initialized
        if not _initialized:
            _initialized = True
            # Register the streaming http handlers with urllib2
            register_openers()
    
        datagen = to_bytes("")
        headers = {}
        if "file" in options:
            file = options["file"]
            if not isinstance(file, string_types):
                datagen, headers = multipart_encode({'file': file})
            elif not re.match(r'^https?:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$', file):
                file_io = open(file, "rb")
                datagen, headers = multipart_encode({'file': file_io})
            else:
                param_list.append(("file", file))
        request = urllib2.Request(api_url + "?" + urlencode(param_list), datagen, headers)
        request.add_header("User-Agent", cloudinary.USER_AGENT)
    
        kw = {}
        if 'timeout' in options:
            kw['timeout'] = options['timeout']

        code = 200
        try:
            response = urllib2.urlopen(request, **kw).read()
        except socket.error:
            e = sys.exc_info()[1]
            raise Error("Socket error: %s" % str(e))
        except urllib2.HTTPError:
            e = sys.exc_info()[1]
            if not e.code in [200, 400, 500]:
                raise Error("Server returned unexpected status code - %d - %s" % (e.code, e.read()))
            code = e.code
            response = e.read()
    
        try:
            result = json.loads(to_string(response))
        except Exception:
            e = sys.exc_info()[1]
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s", code, response, e)
    
        if "error" in result:
            if return_error:
                result["error"]["http_code"] = code
            else:
                raise Error(result["error"]["message"])
    
        return result
    finally:
        if file_io: file_io.close()    
Пример #10
0
def call_api(action, params, **options):
    try:
        file_io = None
        return_error = options.get("return_error")
        if options.get("unsigned"):
            params = utils.cleanup_params(params)
        else:
            params = utils.sign_request(params, options)

        param_list = []
        for k, v in params.items():
            if isinstance(v, list):
                for vv in v:
                    param_list.append((k + "[]", vv))
            elif v:
                param_list.append((k, v))

        api_url = utils.cloudinary_api_url(action, **options)

        global _initialized
        if not _initialized:
            _initialized = True
            # Register the streaming http handlers with urllib2
            register_openers()

        datagen = to_bytes("")
        headers = {}
        if "file" in options:
            file = options["file"]
            if not isinstance(file, string_types):
                datagen, headers = multipart_encode({'file': file})
            elif not re.match(
                    r'^https?:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$',
                    file):
                file_io = open(file, "rb")
                datagen, headers = multipart_encode({'file': file_io})
            else:
                param_list.append(("file", file))
        request = urllib2.Request(api_url + "?" + urlencode(param_list),
                                  datagen, headers)
        request.add_header("User-Agent", cloudinary.USER_AGENT)

        code = 200
        try:
            response = urllib2.urlopen(request).read()
        except urllib2.HTTPError:
            e = sys.exc_info()[1]
            if not e.code in [200, 400, 500]:
                raise Error(
                    "Server returned unexpected status code - %d - %s" %
                    (e.code, e.read()))
            code = e.code
            response = e.read()

        try:
            result = json.loads(to_string(response))
        except Exception:
            e = sys.exc_info()[1]
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s",
                        code, response, e)

        if "error" in result:
            if return_error:
                result["error"]["http_code"] = response.code
            else:
                raise Error(result["error"]["message"])

        return result
    finally:
        if file_io: file_io.close()
Пример #11
0
def call_api(action,
             params,
             http_headers={},
             return_error=False,
             unsigned=False,
             file=None,
             timeout=None,
             **options):
    try:
        file_io = None
        if unsigned:
            params = utils.cleanup_params(params)
        else:
            params = utils.sign_request(params, options)

        param_list = []
        for k, v in params.items():
            if isinstance(v, list):
                for vv in v:
                    param_list.append((k + "[]", vv))
            elif v:
                param_list.append((k, v))

        api_url = utils.cloudinary_api_url(action, **options)

        global _initialized
        if not _initialized:
            _initialized = True
            # Register the streaming http handlers with urllib2
            register_openers()

        datagen, headers = multipart_encode({})
        if file:
            if not isinstance(file, string_types):
                datagen, headers = multipart_encode({'file': file})
            elif not re.match(
                    r'ftp:|https?:|s3:|data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$',
                    file):
                file_io = open(file, "rb")
                datagen, headers = multipart_encode({'file': file_io})
            else:
                param_list.append(("file", file))

        if _is_gae():
            # Might not be needed in the future but for now this is needed in GAE
            datagen = "".join(datagen)

        request = urllib2.Request(api_url + "?" + urlencode(param_list),
                                  datagen, headers)
        request.add_header("User-Agent", cloudinary.get_user_agent())
        for k, v in http_headers.items():
            request.add_header(k, v)

        kw = {}
        if timeout is not None:
            kw['timeout'] = timeout

        code = 200
        try:
            response = urllib2.urlopen(request, **kw).read()
        except HTTPError:
            e = sys.exc_info()[1]
            if not e.code in [200, 400, 500]:
                raise Error(
                    "Server returned unexpected status code - %d - %s" %
                    (e.code, e.read()))
            code = e.code
            response = e.read()
        except urllib2.URLError:
            e = sys.exc_info()[1]
            raise Error("Error - %s" % str(e))
        except socket.error:
            e = sys.exc_info()[1]
            raise Error("Socket error: %s" % str(e))

        try:
            result = json.loads(to_string(response))
        except Exception:
            e = sys.exc_info()[1]
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s",
                        code, response, e)

        if "error" in result:
            if return_error:
                result["error"]["http_code"] = code
            else:
                raise Error(result["error"]["message"])

        return result
    finally:
        if file_io: file_io.close()