def _convert_mod_error(error):
    message = error.message.replace(
        "The condition specified using HTTP conditional header(s) is not met.",
        "The specified blob already exists.")
    message = message.replace("ConditionNotMet", "BlobAlreadyExists")
    overwrite_error = ResourceExistsError(message=message,
                                          response=error.response,
                                          error=error)
    overwrite_error.error_code = StorageErrorCode.blob_already_exists
    raise overwrite_error
Пример #2
0
def deserialize_queue_creation(response, obj, headers):
    if response.status_code == 204:
        error_code = StorageErrorCode.queue_already_exists
        error = ResourceExistsError(
            message="Queue already exists\nRequestId:{}\nTime:{}\nErrorCode:{}"
            .format(headers['x-ms-request-id'], headers['Date'], error_code),
            response=response)
        error.error_code = error_code
        error.additional_info = {}
        raise error
    return headers
def _deserialize_table_creation(response, _, headers):
    if response.status_code == 204:
        error_code = TableErrorCode.table_already_exists
        error = ResourceExistsError(
            message="Table already exists\nRequestId:{}\nTime:{}\nErrorCode:{}"
            .format(headers["x-ms-request-id"], headers["Date"], error_code),
            response=response,
        )
        error.error_code = error_code
        error.additional_info = {}
        raise error
    return headers
Пример #4
0
    def upload_blob(self, data, length=None):
        if self.blob in self.container.blobs:
            raise ResourceExistsError("Blob already exists")

        if length is not None and length != len(data):
            raise ValueError("Wrong length for blob data!")

        self.container.blobs[self.blob] = data
Пример #5
0
def insert_entity(client, entity, if_exists='fail'):
    from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError
    if if_exists == 'fail':
        partition_key = entity.get('PartitionKey')
        row_key = entity.get('RowKey')
        try:
            client.get_entity(partition_key, row_key)
            raise ResourceExistsError("The specified entity already exists.")
        except ResourceNotFoundError:
            return client.upsert_entity(entity)
    if if_exists == 'merge' or if_exists == 'replace':
        return client.upsert_entity(entity, mode=if_exists)
    from knack.util import CLIError
    raise CLIError("Unrecognized value '{}' for --if-exists".format(if_exists))
    def _save(self, name, content):
        cleaned_name = clean_name(name)
        name = self._get_valid_path(name)
        params = self._get_content_settings_parameters(name, content)

        # Unwrap django file (wrapped by parent's save call)
        if isinstance(content, File):
            content = content.file

        content.seek(0)
        try:
            self.service.upload_blob(
                name=name,
                data=content.read(),
                content_settings=ContentSettings(**params),
                max_concurrency=self.upload_max_conn,
                timeout=self.timeout,
                overwrite=self.overwrite_files)
        except ResourceExistsError():
            logger.info(
                f"Blob {name} already exists and the overwrite flag is set to False."
            )

        return cleaned_name
Пример #7
0
    def _update_initial(
        self,
        resource_group_name,  # type: str
        cluster_rp,  # type: Union[str, "_models.Enum0"]
        cluster_resource_name,  # type: Union[str, "_models.Enum1"]
        cluster_name,  # type: str
        extension_name,  # type: str
        patch_extension,  # type: "_models.PatchExtension"
        **kwargs  # type: Any
    ):
        # type: (...) -> "_models.Extension"
        cls = kwargs.pop('cls', None)  # type: ClsType["_models.Extension"]
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: lambda response: ResourceExistsError(response=response, model=self._deserialize(_models.ErrorResponse, response), error_format=ARMErrorFormat),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2021-09-01"
        content_type = kwargs.pop("content_type", "application/json")
        accept = "application/json"

        # Construct URL
        url = self._update_initial.metadata['url']  # type: ignore
        path_format_arguments = {
            'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str', min_length=1),
            'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str', max_length=90, min_length=1),
            'clusterRp': self._serialize.url("cluster_rp", cluster_rp, 'str'),
            'clusterResourceName': self._serialize.url("cluster_resource_name", cluster_resource_name, 'str'),
            'clusterName': self._serialize.url("cluster_name", cluster_name, 'str'),
            'extensionName': self._serialize.url("extension_name", extension_name, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(patch_extension, 'PatchExtension')
        body_content_kwargs['content'] = body_content
        request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
        pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize('Extension', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized
    async def create_conversion(
        self,
        account_id: str,
        conversion_id: str,
        body: "models.CreateAssetConversionSettings",
        **kwargs
    ) -> "models.AssetConversion":
        """Creates a conversion using an asset stored in an Azure Blob Storage account.

        Creates a conversion using an asset stored in an Azure Blob Storage account.

        :param account_id: The Azure Remote Rendering account ID.
        :type account_id: str
        :param conversion_id: An ID uniquely identifying the conversion for the given account. The ID
         is case sensitive, can contain any combination of alphanumeric characters including hyphens and
         underscores, and cannot contain more than 256 characters.
        :type conversion_id: str
        :param body: Request body configuring the settings for an asset conversion.
        :type body: ~azure.mixedreality.remoterendering._generated.models.CreateAssetConversionSettings
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AssetConversion, or the result of cls(response)
        :rtype: ~azure.mixedreality.remoterendering._generated.models.AssetConversion
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        cls = kwargs.pop('cls', None)  # type: ClsType["models.AssetConversion"]
        error_map = {
            404: ResourceNotFoundError,
            400: lambda response: HttpResponseError(response=response, model=self._deserialize(models.ErrorResponse, response)),
            409: lambda response: ResourceExistsError(response=response, model=self._deserialize(models.ErrorResponse, response)),
            500: lambda response: HttpResponseError(response=response, model=self._deserialize(models.ErrorResponse, response)),
        }
        error_map.update(kwargs.pop('error_map', {}))
        api_version = "2021-01-01"
        content_type = kwargs.pop("content_type", "application/json")

        # Construct URL
        url = self.create_conversion.metadata['url']  # type: ignore
        path_format_arguments = {
            'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
            'account_id': self._serialize.url("account_id", account_id, 'str'),
            'conversion_id': self._serialize.url("conversion_id", conversion_id, 'str'),
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}  # type: Dict[str, Any]
        query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')

        # Construct headers
        header_parameters = {}  # type: Dict[str, Any]
        header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
        header_parameters['Accept'] = 'application/json'

        body_content_kwargs = {}  # type: Dict[str, Any]
        body_content = self._serialize.body(body, 'CreateAssetConversionSettings')
        body_content_kwargs['content'] = body_content
        request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)

        pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
        response = pipeline_response.http_response

        if response.status_code not in [200, 201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        if response.status_code == 200:
            response_headers['MS-CV']=self._deserialize('str', response.headers.get('MS-CV'))
            deserialized = self._deserialize('AssetConversion', pipeline_response)

        if response.status_code == 201:
            response_headers['MS-CV']=self._deserialize('str', response.headers.get('MS-CV'))
            deserialized = self._deserialize('AssetConversion', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, response_headers)

        return deserialized