Esempio n. 1
0
def cloudinary_direct_upload(callback_url, **options):
    params = uploader.build_upload_params(callback=callback_url, **options)
    params = utils.sign_request(params, options)    
    
    api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), upload_prefix=options.get("upload_prefix"))

    return {"params": params, "url": api_url}
Esempio n. 2
0
def cloudinary_direct_upload(callback_url, **options):
    params = utils.build_upload_params(callback=callback_url, **options)
    params = utils.sign_request(params, options)    
    
    api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), upload_prefix=options.get("upload_prefix"))

    return {"params": params, "url": api_url}
Esempio n. 3
0
def cloudinary_direct_upload(callback_url, **options):
    """Deprecated - please use cloudinary_direct_upload_field, or a proper form"""
    params = utils.build_upload_params(callback=callback_url, **options)
    params = utils.sign_request(params, options)

    api_url = utils.cloudinary_api_url(
        "upload",
        resource_type=options.get("resource_type", "image"),
        upload_prefix=options.get("upload_prefix"))

    return {"params": params, "url": api_url}
Esempio n. 4
0
def cloudinary_direct_upload(callback_url, **options):
  params = uploader.build_upload_params(callback=callback_url, **options)  
  params["signature"] = utils.api_sign_request(params, cloudinary.config().api_secret)  
  params["api_key"] = cloudinary.config().api_key
  
  api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), upload_prefix=options.get("upload_prefix"))

  for k, v in params.items():
    if not v:
      del params[k]

  return {"params": params, "url": api_url}
Esempio n. 5
0
def cloudinary_direct_upload(callback_url, **options):
    params = uploader.build_upload_params(callback=callback_url, **options)    
    params["signature"] = utils.api_sign_request(params, cloudinary.config().api_secret)    
    params["api_key"] = cloudinary.config().api_key
    
    api_url = utils.cloudinary_api_url("upload", resource_type=options.get("resource_type", "image"), upload_prefix=options.get("upload_prefix"))

    for k, v in params.items():
        if not v:
            del params[k]

    return {"params": params, "url": api_url}
Esempio n. 6
0
def call_api(action, params, **options):
    return_error = options.get("return_error")
    api_key = options.get("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.get("api_secret", cloudinary.config().api_secret)
    if not api_secret: raise Exception("Must supply api_secret")

    params["signature"] = utils.api_sign_request(params, api_secret)
    params["api_key"] = api_key

    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 = {}
    if "file" in options:
        file = options["file"]
        if not isinstance(file, basestring):
            datagen, headers = multipart_encode({'file': file})
        elif not re.match(r'^https?:', file):
            datagen, headers = multipart_encode({'file': open(file, "rb")})
        else:
            param_list.append(("file", file))
    request = urllib2.Request(api_url + "?" + urllib.urlencode(param_list), datagen, headers)

    code = 200
    try:
        response = urllib2.urlopen(request).read()
    except urllib2.HTTPError, e:
        if not e.code in [200, 400, 500]:
            raise Exception("Server returned unexpected status code - %d - %s" % (e.code, e.read()))
        code = e.code
        response = e.read()
Esempio n. 7
0
def call_api(action, params, **options):
    return_error = options.get("return_error")
    api_key = options.get("api_key", cloudinary.config().api_key)
    if not api_key: raise Exception("Must supply api_key")
    api_secret = options.get("api_secret", cloudinary.config().api_secret)
    if not api_secret: raise Exception("Must supply api_secret")

    params["signature"] = utils.api_sign_request(params, api_secret)
    params["api_key"] = api_key

    # Remove blank parameters
    for k, v in params.items():
        if not v:
            del params[k]

    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 = {}
    if "file" in options:
        file = options["file"]
        if not isinstance(file, basestring):
            datagen, headers = multipart_encode({'file': file})
        elif not re.match(r'^https?:', file):
            datagen, headers = multipart_encode({'file': open(file)})
        else:
            params["file"] = file
    request = urllib2.Request(api_url + "?" + urllib.urlencode(params),
                              datagen, headers)

    code = 200
    try:
        response = urllib2.urlopen(request).read()
    except urllib2.HTTPError, e:
        if not e.code in [200, 400, 500]:
            raise Exception(
                "Server returned unexpected status code - %d - %s" %
                (e.code, e.read()))
        code = e.code
        response = e.read()
Esempio n. 8
0
def call_api(action, params, **options):
    return_error = options.get("return_error")
    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 = {}
    if "file" in options:
        file = options["file"]
        if not isinstance(file, basestring):
            datagen, headers = multipart_encode({'file': file})
        elif not re.match(
                r'^https?:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$',
                file):
            datagen, headers = multipart_encode({'file': open(file, "rb")})
        else:
            param_list.append(("file", file))
    request = urllib2.Request(api_url + "?" + urllib.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:
        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()
Esempio n. 9
0
def call_api(action, params, **options):
    return_error = options.get("return_error")
    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 = {}
    if "file" in options:
        file = options["file"]
        if not isinstance(file, basestring):
            datagen, headers = multipart_encode({'file': file})
        elif not re.match(r'^https?:|^s3:|^data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$', file):
            datagen, headers = multipart_encode({'file': open(file, "rb")})
        else:
            param_list.append(("file", file))
    request = urllib2.Request(api_url + "?" + urllib.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:
        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()
Esempio n. 10
0
def call_api(action,
             params,
             http_headers=None,
             return_error=False,
             unsigned=False,
             file=None,
             timeout=None,
             **options):
    if http_headers is None:
        http_headers = {}
    file_io = None
    try:
        if unsigned:
            params = utils.cleanup_params(params)
        else:
            params = utils.sign_request(params, options)

        param_list = OrderedDict()
        for k, v in params.items():
            if isinstance(v, list):
                for i in range(len(v)):
                    param_list["{0}[{1}]".format(k, i)] = v[i]
            elif v:
                param_list[k] = v

        api_url = utils.cloudinary_api_url(action, **options)
        if file:
            if isinstance(file, string_types):
                if utils.is_remote_url(file):
                    # URL
                    name = None
                    data = file
                else:
                    # file path
                    name = file
                    with open(file, "rb") as opened:
                        data = opened.read()
            elif hasattr(file, 'read') and callable(file.read):
                # stream
                data = file.read()
                name = file.name if hasattr(file, 'name') and isinstance(
                    file.name, str) else "stream"
            elif isinstance(file, tuple):
                name = None
                data = file
            else:
                # Not a string, not a stream
                name = "file"
                data = file

            param_list["file"] = (name, data) if name else data

        headers = {"User-Agent": cloudinary.get_user_agent()}
        headers.update(http_headers)

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

        code = 200
        try:
            response = _http.request("POST", api_url, param_list, headers,
                                     **kw)
        except HTTPError as e:
            raise Error("Unexpected error - {0!r}".format(e))
        except socket.error as e:
            raise Error("Socket error: {0!r}".format(e))

        try:
            result = json.loads(response.data.decode('utf-8'))
        except Exception as e:
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s",
                        response.status, response, e)

        if "error" in result:
            if response.status not in [200, 400, 401, 403, 404, 500]:
                code = response.status
            if return_error:
                result["error"]["http_code"] = code
            else:
                raise Error(result["error"]["message"])

        return result
    finally:
        if file_io:
            file_io.close()
Esempio n. 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()    
Esempio n. 12
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()

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

        datagen, headers = multipart_encode(param_list)

        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, 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()
Esempio n. 13
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()    
Esempio n. 14
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()
Esempio n. 15
0
def call_api(action,
             params,
             http_headers=None,
             return_error=False,
             unsigned=False,
             file=None,
             timeout=None,
             **options):
    params = utils.cleanup_params(params)

    headers = {"User-Agent": cloudinary.get_user_agent()}

    if http_headers is not None:
        headers.update(http_headers)

    oauth_token = options.get("oauth_token", cloudinary.config().oauth_token)

    if oauth_token:
        headers["authorization"] = "Bearer {}".format(oauth_token)
    elif not unsigned:
        params = utils.sign_request(params, options)

    param_list = []
    for k, v in params.items():
        if isinstance(v, list):
            for i in v:
                param_list.append(("{0}[]".format(k), i))
        elif v:
            param_list.append((k, v))

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

    if file:
        filename = options.get(
            "filename"
        )  # Custom filename provided by user (relevant only for streams and files)

        if isinstance(file, string_types):
            if utils.is_remote_url(file):
                # URL
                name = None
                data = file
            else:
                # file path
                name = filename or file
                with open(file, "rb") as opened:
                    data = opened.read()
        elif hasattr(file, 'read') and callable(file.read):
            # stream
            data = file.read()
            name = filename or (file.name if hasattr(file, 'name')
                                and isinstance(file.name, str) else "stream")
        elif isinstance(file, tuple):
            name, data = file
        else:
            # Not a string, not a stream
            name = filename or "file"
            data = file

        param_list.append(("file", (name, data) if name else data))

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

    code = 200
    try:
        response = _http.request("POST", api_url, param_list, headers, **kw)
    except HTTPError as e:
        raise Error("Unexpected error - {0!r}".format(e))
    except socket.error as e:
        raise Error("Socket error: {0!r}".format(e))

    try:
        result = json.loads(response.data.decode('utf-8'))
    except Exception as e:
        # Error is parsing json
        raise Error("Error parsing server response (%d) - %s. Got - %s" %
                    (response.status, response.data, e))

    if "error" in result:
        if response.status not in [200, 400, 401, 403, 404, 500]:
            code = response.status
        if return_error:
            result["error"]["http_code"] = code
        else:
            raise Error(result["error"]["message"])

    return result
Esempio n. 16
0
def call_api(action, params, http_headers=None, return_error=False, unsigned=False, file=None, timeout=None, **options):
    if http_headers is None:
        http_headers = {}
    file_io = None
    try:
        if unsigned:
            params = utils.cleanup_params(params)
        else:
            params = utils.sign_request(params, options)

        param_list = OrderedDict()
        for k, v in params.items():
            if isinstance(v, list):
                for i in range(len(v)):
                    param_list["{0}[{1}]".format(k, i)] = v[i]
            elif v:
                param_list[k] = v

        api_url = utils.cloudinary_api_url(action, **options)
        if file:
            if isinstance(file, string_types):
                if re.match(r'ftp:|https?:|s3:|data:[^;]*;base64,([a-zA-Z0-9\/+\n=]+)$', file):
                    # URL
                    name = None
                    data = file
                else:
                    # file path
                    name = file
                    with open(file, "rb") as opened:
                        data = opened.read()
            elif hasattr(file, 'read') and callable(file.read):
                # stream
                data = file.read()
                name = file.name if hasattr(file, 'name') else "stream"
            elif isinstance(file, tuple):
                name = None
                data = file
            else:
                # Not a string, not a stream
                name = "file"
                data = file

            param_list["file"] = (name, data) if name else data

        headers = {"User-Agent": cloudinary.get_user_agent()}
        headers.update(http_headers)

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

        code = 200
        try:
            response = _http.request("POST", api_url, param_list, headers, **kw)
        except HTTPError as e:
            raise Error("Unexpected error - {0!r}".format(e))
        except socket.error as e:
            raise Error("Socket error: {0!r}".format(e))

        try:
            result = json.loads(response.data.decode('utf-8'))
        except Exception as e:
            # Error is parsing json
            raise Error("Error parsing server response (%d) - %s. Got - %s", response.status, response, e)

        if "error" in result:
            if response.status not in [200, 400, 401, 403, 404, 500]:
                code = response.status
            if return_error:
                    result["error"]["http_code"] = code
            else:
                raise Error(result["error"]["message"])

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