diff --git a/sdk/communication/azure-communication-jobrouter/_meta.json b/sdk/communication/azure-communication-jobrouter/_meta.json
new file mode 100644
index 000000000000..e84580305598
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/_meta.json
@@ -0,0 +1,6 @@
+{
+ "commit": "26af8eff710ea634da1b33fed369967d1c39b689",
+ "repository_url": "https://github.com/Azure/azure-rest-api-specs",
+ "typespec_src": "specification/communication/Communication.JobRouter",
+ "@azure-tools/typespec-python": "0.36.1"
+}
\ No newline at end of file
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py
index ba2b07fc1b38..b25a83281bd8 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py
@@ -5,16 +5,22 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import JobRouterAdministrationClient
-from ._patch import JobRouterClient
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+from ._client import JobRouterAdministrationClient # type: ignore
+from ._client import JobRouterClient # type: ignore
from ._version import VERSION
__version__ = VERSION
try:
from ._patch import __all__ as _patch_all
- from ._patch import * # pylint: disable=unused-wildcard-import
+ from ._patch import *
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk
@@ -23,6 +29,6 @@
"JobRouterAdministrationClient",
"JobRouterClient",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py
deleted file mode 100644
index 8f826623df34..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# ------------------------------------
-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-# ------------------------------------
-
-from enum import Enum
-from azure.core import CaseInsensitiveEnumMeta
-
-
-class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta):
- V2022_07_18_PREVIEW = "2022-07-18-preview"
- V2023_11_01 = "2023-11-01"
- V2024_01_18_PREVIEW = "2024-01-18-preview"
-
-
-DEFAULT_VERSION = ApiVersion.V2024_01_18_PREVIEW.value
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py
index 24fcd9ae2500..6c8e59cf3bb1 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py
@@ -8,6 +8,7 @@
from copy import deepcopy
from typing import Any
+from typing_extensions import Self
from azure.core import PipelineClient
from azure.core.pipeline import policies
@@ -18,9 +19,7 @@
from ._serialization import Deserializer, Serializer
-class JobRouterAdministrationClient(
- JobRouterAdministrationClientOperationsMixin
-): # pylint: disable=client-accepts-api-version-keyword
+class JobRouterAdministrationClient(JobRouterAdministrationClientOperationsMixin):
"""JobRouterAdministrationClient.
:param endpoint: Uri of your Communication resource. Required.
@@ -79,7 +78,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
request_copy = deepcopy(request)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
@@ -88,7 +87,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
def close(self) -> None:
self._client.close()
- def __enter__(self) -> "JobRouterAdministrationClient":
+ def __enter__(self) -> Self:
self._client.__enter__()
return self
@@ -96,7 +95,7 @@ def __exit__(self, *exc_details: Any) -> None:
self._client.__exit__(*exc_details)
-class JobRouterClient(JobRouterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
+class JobRouterClient(JobRouterClientOperationsMixin):
"""JobRouterClient.
:param endpoint: Uri of your Communication resource. Required.
@@ -155,7 +154,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
request_copy = deepcopy(request)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
@@ -164,7 +163,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs:
def close(self) -> None:
self._client.close()
- def __enter__(self) -> "JobRouterClient":
+ def __enter__(self) -> Self:
self._client.__enter__()
return self
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py
index 1e52a5a93939..fc65d13a56aa 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py
@@ -51,7 +51,7 @@ def _configure(self, **kwargs: Any) -> None:
self.authentication_policy = kwargs.get("authentication_policy")
-class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long
+class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes
"""Configuration for JobRouterClient.
Note that all parameters used to create this instance are saved as instance
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py
index 1ddc071517d6..e6a2730f9276 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py
@@ -1,11 +1,13 @@
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
-# pylint: disable=protected-access, arguments-differ, signature-differs, broad-except
+# pylint: disable=protected-access, broad-except
+import copy
import calendar
import decimal
import functools
@@ -13,12 +15,12 @@
import logging
import base64
import re
-import copy
import typing
import enum
import email.utils
from datetime import datetime, date, time, timedelta, timezone
from json import JSONEncoder
+import xml.etree.ElementTree as ET
from typing_extensions import Self
import isodate
from azure.core.exceptions import DeserializationError
@@ -123,7 +125,7 @@ def _serialize_datetime(o, format: typing.Optional[str] = None):
def _is_readonly(p):
try:
- return p._visibility == ["read"] # pylint: disable=protected-access
+ return p._visibility == ["read"]
except AttributeError:
return False
@@ -286,6 +288,12 @@ def _deserialize_decimal(attr):
return decimal.Decimal(str(attr))
+def _deserialize_int_as_str(attr):
+ if isinstance(attr, int):
+ return attr
+ return int(attr)
+
+
_DESERIALIZE_MAPPING = {
datetime: _deserialize_datetime,
date: _deserialize_date,
@@ -307,9 +315,11 @@ def _deserialize_decimal(attr):
def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None):
+ if annotation is int and rf and rf._format == "str":
+ return _deserialize_int_as_str
if rf and rf._format:
return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format)
- return _DESERIALIZE_MAPPING.get(annotation)
+ return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore
def _get_type_alias_type(module_name: str, alias_name: str):
@@ -339,7 +349,7 @@ def _get_model(module_name: str, model_name: str):
class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object
def __init__(self, data: typing.Dict[str, typing.Any]) -> None:
- self._data = copy.deepcopy(data)
+ self._data = data
def __contains__(self, key: typing.Any) -> bool:
return key in self._data
@@ -378,16 +388,13 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any:
return default
@typing.overload
- def pop(self, key: str) -> typing.Any:
- ...
+ def pop(self, key: str) -> typing.Any: ...
@typing.overload
- def pop(self, key: str, default: _T) -> _T:
- ...
+ def pop(self, key: str, default: _T) -> _T: ...
@typing.overload
- def pop(self, key: str, default: typing.Any) -> typing.Any:
- ...
+ def pop(self, key: str, default: typing.Any) -> typing.Any: ...
def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any:
if default is _UNSET:
@@ -404,12 +411,10 @@ def update(self, *args: typing.Any, **kwargs: typing.Any) -> None:
self._data.update(*args, **kwargs)
@typing.overload
- def setdefault(self, key: str, default: None = None) -> None:
- ...
+ def setdefault(self, key: str, default: None = None) -> None: ...
@typing.overload
- def setdefault(self, key: str, default: typing.Any) -> typing.Any:
- ...
+ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ...
def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any:
if default is _UNSET:
@@ -446,6 +451,10 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m
return float(o)
if isinstance(o, enum.Enum):
return o.value
+ if isinstance(o, int):
+ if format == "str":
+ return str(o)
+ return o
try:
# First try datetime.datetime
return _serialize_datetime(o, format)
@@ -476,11 +485,16 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin
return value
if rf._is_model:
return _deserialize(rf._type, value)
+ if isinstance(value, ET.Element):
+ value = _deserialize(rf._type, value)
return _serialize(value, rf._format)
class Model(_MyMutableMapping):
_is_model = True
+ # label whether current class's _attr_to_rest_field has been calculated
+ # could not see _attr_to_rest_field directly because subclass inherits it from parent class
+ _calculated: typing.Set[str] = set()
def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
class_name = self.__class__.__name__
@@ -491,10 +505,58 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
for rest_field in self._attr_to_rest_field.values()
if rest_field._default is not _UNSET
}
- if args:
- dict_to_pass.update(
- {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()}
- )
+ if args: # pylint: disable=too-many-nested-blocks
+ if isinstance(args[0], ET.Element):
+ existed_attr_keys = []
+ model_meta = getattr(self, "_xml", {})
+
+ for rf in self._attr_to_rest_field.values():
+ prop_meta = getattr(rf, "_xml", {})
+ xml_name = prop_meta.get("name", rf._rest_name)
+ xml_ns = prop_meta.get("ns", model_meta.get("ns", None))
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+
+ # attribute
+ if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name))
+ continue
+
+ # unwrapped element is array
+ if prop_meta.get("unwrapped", False):
+ # unwrapped array could either use prop items meta/prop meta
+ if prop_meta.get("itemsName"):
+ xml_name = prop_meta.get("itemsName")
+ xml_ns = prop_meta.get("itemNs")
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+ items = args[0].findall(xml_name) # pyright: ignore
+ if len(items) > 0:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, items)
+ continue
+
+ # text element is primitive type
+ if prop_meta.get("text", False):
+ if args[0].text is not None:
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text)
+ continue
+
+ # wrapped element could be normal property or array, it should only have one element
+ item = args[0].find(xml_name)
+ if item is not None:
+ existed_attr_keys.append(xml_name)
+ dict_to_pass[rf._rest_name] = _deserialize(rf._type, item)
+
+ # rest thing is additional properties
+ for e in args[0]:
+ if e.tag not in existed_attr_keys:
+ dict_to_pass[e.tag] = _convert_element(e)
+ else:
+ dict_to_pass.update(
+ {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()}
+ )
else:
non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field]
if non_attr_kwargs:
@@ -512,55 +574,70 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None:
def copy(self) -> "Model":
return Model(self.__dict__)
- def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument
- # we know the last three classes in mro are going to be 'Model', 'dict', and 'object'
- mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order
- attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
- k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
- }
- annotations = {
- k: v
- for mro_class in mros
- if hasattr(mro_class, "__annotations__") # pylint: disable=no-member
- for k, v in mro_class.__annotations__.items() # pylint: disable=no-member
- }
- for attr, rf in attr_to_rest_field.items():
- rf._module = cls.__module__
- if not rf._type:
- rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None))
- if not rf._rest_name_input:
- rf._rest_name_input = attr
- cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items())
+ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self:
+ if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated:
+ # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping',
+ # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object'
+ mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order
+ attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property
+ k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type")
+ }
+ annotations = {
+ k: v
+ for mro_class in mros
+ if hasattr(mro_class, "__annotations__")
+ for k, v in mro_class.__annotations__.items()
+ }
+ for attr, rf in attr_to_rest_field.items():
+ rf._module = cls.__module__
+ if not rf._type:
+ rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None))
+ if not rf._rest_name_input:
+ rf._rest_name_input = attr
+ cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items())
+ cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}")
return super().__new__(cls) # pylint: disable=no-value-for-parameter
def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None:
for base in cls.__bases__:
- if hasattr(base, "__mapping__"): # pylint: disable=no-member
- base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member
+ if hasattr(base, "__mapping__"):
+ base.__mapping__[discriminator or cls.__name__] = cls # type: ignore
@classmethod
- def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]:
+ def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]:
for v in cls.__dict__.values():
- if (
- isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators
- ): # pylint: disable=protected-access
- return v._rest_name # pylint: disable=protected-access
+ if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators:
+ return v
return None
@classmethod
def _deserialize(cls, data, exist_discriminators):
- if not hasattr(cls, "__mapping__"): # pylint: disable=no-member
+ if not hasattr(cls, "__mapping__"):
return cls(data)
discriminator = cls._get_discriminator(exist_discriminators)
- exist_discriminators.append(discriminator)
- mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member
- if mapped_cls == cls:
+ if discriminator is None:
return cls(data)
- return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access
+ exist_discriminators.append(discriminator._rest_name)
+ if isinstance(data, ET.Element):
+ model_meta = getattr(cls, "_xml", {})
+ prop_meta = getattr(discriminator, "_xml", {})
+ xml_name = prop_meta.get("name", discriminator._rest_name)
+ xml_ns = prop_meta.get("ns", model_meta.get("ns", None))
+ if xml_ns:
+ xml_name = "{" + xml_ns + "}" + xml_name
+
+ if data.get(xml_name) is not None:
+ discriminator_value = data.get(xml_name)
+ else:
+ discriminator_value = data.find(xml_name).text # pyright: ignore
+ else:
+ discriminator_value = data.get(discriminator._rest_name)
+ mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore
+ return mapped_cls._deserialize(data, exist_discriminators)
def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]:
- """Return a dict that can be JSONify using json.dump.
+ """Return a dict that can be turned into json using json.dump.
:keyword bool exclude_readonly: Whether to remove the readonly properties.
:returns: A dict JSON compatible object
@@ -568,6 +645,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.
"""
result = {}
+ readonly_props = []
if exclude_readonly:
readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)]
for k, v in self.items():
@@ -594,12 +672,74 @@ def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any:
return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v
-def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912
+def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj):
+ if _is_model(obj):
+ return obj
+ return _deserialize(model_deserializer, obj)
+
+
+def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj):
+ if obj is None:
+ return obj
+ return _deserialize_with_callable(if_obj_deserializer, obj)
+
+
+def _deserialize_with_union(deserializers, obj):
+ for deserializer in deserializers:
+ try:
+ return _deserialize(deserializer, obj)
+ except DeserializationError:
+ pass
+ raise DeserializationError()
+
+
+def _deserialize_dict(
+ value_deserializer: typing.Optional[typing.Callable],
+ module: typing.Optional[str],
+ obj: typing.Dict[typing.Any, typing.Any],
+):
+ if obj is None:
+ return obj
+ if isinstance(obj, ET.Element):
+ obj = {child.tag: child for child in obj}
+ return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()}
+
+
+def _deserialize_multiple_sequence(
+ entry_deserializers: typing.List[typing.Optional[typing.Callable]],
+ module: typing.Optional[str],
+ obj,
+):
+ if obj is None:
+ return obj
+ return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers))
+
+
+def _deserialize_sequence(
+ deserializer: typing.Optional[typing.Callable],
+ module: typing.Optional[str],
+ obj,
+):
+ if obj is None:
+ return obj
+ if isinstance(obj, ET.Element):
+ obj = list(obj)
+ return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)
+
+
+def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]:
+ return sorted(
+ types,
+ key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"),
+ )
+
+
+def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches
annotation: typing.Any,
module: typing.Optional[str],
rf: typing.Optional["_RestField"] = None,
) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]:
- if not annotation or annotation in [int, float]:
+ if not annotation:
return None
# is it a type alias?
@@ -621,11 +761,6 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915,
if rf:
rf._is_model = True
- def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj):
- if _is_model(obj):
- return obj
- return _deserialize(model_deserializer, obj)
-
return functools.partial(_deserialize_model, annotation) # pyright: ignore
except Exception:
pass
@@ -640,36 +775,27 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj
# is it optional?
try:
if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore
- if_obj_deserializer = _get_deserialize_callable_from_annotation(
- next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore
- )
-
- def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj):
- if obj is None:
- return obj
- return _deserialize_with_callable(if_obj_deserializer, obj)
-
- return functools.partial(_deserialize_with_optional, if_obj_deserializer)
+ if len(annotation.__args__) <= 2: # pyright: ignore
+ if_obj_deserializer = _get_deserialize_callable_from_annotation(
+ next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore
+ )
+
+ return functools.partial(_deserialize_with_optional, if_obj_deserializer)
+ # the type is Optional[Union[...]], we need to remove the None type from the Union
+ annotation_copy = copy.copy(annotation)
+ annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore
+ return _get_deserialize_callable_from_annotation(annotation_copy, module, rf)
except AttributeError:
pass
+ # is it union?
if getattr(annotation, "__origin__", None) is typing.Union:
# initial ordering is we make `string` the last deserialization option, because it is often them most generic
deserializers = [
_get_deserialize_callable_from_annotation(arg, module, rf)
- for arg in sorted(
- annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore
- )
+ for arg in _sorted_annotations(annotation.__args__) # pyright: ignore
]
- def _deserialize_with_union(deserializers, obj):
- for deserializer in deserializers:
- try:
- return _deserialize(deserializer, obj)
- except DeserializationError:
- pass
- raise DeserializationError()
-
return functools.partial(_deserialize_with_union, deserializers)
try:
@@ -678,53 +804,26 @@ def _deserialize_with_union(deserializers, obj):
annotation.__args__[1], module, rf # pyright: ignore
)
- def _deserialize_dict(
- value_deserializer: typing.Optional[typing.Callable],
- obj: typing.Dict[typing.Any, typing.Any],
- ):
- if obj is None:
- return obj
- return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()}
-
return functools.partial(
_deserialize_dict,
value_deserializer,
+ module,
)
except (AttributeError, IndexError):
pass
try:
if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore
if len(annotation.__args__) > 1: # pyright: ignore
-
- def _deserialize_multiple_sequence(
- entry_deserializers: typing.List[typing.Optional[typing.Callable]],
- obj,
- ):
- if obj is None:
- return obj
- return type(obj)(
- _deserialize(deserializer, entry, module)
- for entry, deserializer in zip(obj, entry_deserializers)
- )
-
entry_deserializers = [
_get_deserialize_callable_from_annotation(dt, module, rf)
for dt in annotation.__args__ # pyright: ignore
]
- return functools.partial(_deserialize_multiple_sequence, entry_deserializers)
+ return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module)
deserializer = _get_deserialize_callable_from_annotation(
annotation.__args__[0], module, rf # pyright: ignore
)
- def _deserialize_sequence(
- deserializer: typing.Optional[typing.Callable],
- obj,
- ):
- if obj is None:
- return obj
- return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)
-
- return functools.partial(_deserialize_sequence, deserializer)
+ return functools.partial(_deserialize_sequence, deserializer, module)
except (TypeError, IndexError, AttributeError, SyntaxError):
pass
@@ -749,12 +848,23 @@ def _deserialize_default(
def _deserialize_with_callable(
deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]],
value: typing.Any,
-):
+): # pylint: disable=too-many-return-statements
try:
if value is None or isinstance(value, _Null):
return None
+ if isinstance(value, ET.Element):
+ if deserializer is str:
+ return value.text or ""
+ if deserializer is int:
+ return int(value.text) if value.text else None
+ if deserializer is float:
+ return float(value.text) if value.text else None
+ if deserializer is bool:
+ return value.text == "true" if value.text else None
if deserializer is None:
return value
+ if deserializer in [int, float, bool]:
+ return deserializer(value)
if isinstance(deserializer, CaseInsensitiveEnumMeta):
try:
return deserializer(value)
@@ -795,6 +905,7 @@ def __init__(
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
):
self._type = type
self._rest_name_input = name
@@ -805,6 +916,7 @@ def __init__(
self._default = default
self._format = format
self._is_multipart_file_input = is_multipart_file_input
+ self._xml = xml if xml is not None else {}
@property
def _class_type(self) -> typing.Any:
@@ -855,6 +967,7 @@ def rest_field(
default: typing.Any = _UNSET,
format: typing.Optional[str] = None,
is_multipart_file_input: bool = False,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
) -> typing.Any:
return _RestField(
name=name,
@@ -863,6 +976,7 @@ def rest_field(
default=default,
format=format,
is_multipart_file_input=is_multipart_file_input,
+ xml=xml,
)
@@ -870,5 +984,176 @@ def rest_discriminator(
*,
name: typing.Optional[str] = None,
type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin
+ visibility: typing.Optional[typing.List[str]] = None,
+ xml: typing.Optional[typing.Dict[str, typing.Any]] = None,
+) -> typing.Any:
+ return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml)
+
+
+def serialize_xml(model: Model, exclude_readonly: bool = False) -> str:
+ """Serialize a model to XML.
+
+ :param Model model: The model to serialize.
+ :param bool exclude_readonly: Whether to exclude readonly properties.
+ :returns: The XML representation of the model.
+ :rtype: str
+ """
+ return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore
+
+
+def _get_element(
+ o: typing.Any,
+ exclude_readonly: bool = False,
+ parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None,
+ wrapped_element: typing.Optional[ET.Element] = None,
+) -> typing.Union[ET.Element, typing.List[ET.Element]]:
+ if _is_model(o):
+ model_meta = getattr(o, "_xml", {})
+
+ # if prop is a model, then use the prop element directly, else generate a wrapper of model
+ if wrapped_element is None:
+ wrapped_element = _create_xml_element(
+ model_meta.get("name", o.__class__.__name__),
+ model_meta.get("prefix"),
+ model_meta.get("ns"),
+ )
+
+ readonly_props = []
+ if exclude_readonly:
+ readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)]
+
+ for k, v in o.items():
+ # do not serialize readonly properties
+ if exclude_readonly and k in readonly_props:
+ continue
+
+ prop_rest_field = _get_rest_field(o._attr_to_rest_field, k)
+ if prop_rest_field:
+ prop_meta = getattr(prop_rest_field, "_xml").copy()
+ # use the wire name as xml name if no specific name is set
+ if prop_meta.get("name") is None:
+ prop_meta["name"] = k
+ else:
+ # additional properties will not have rest field, use the wire name as xml name
+ prop_meta = {"name": k}
+
+ # if no ns for prop, use model's
+ if prop_meta.get("ns") is None and model_meta.get("ns"):
+ prop_meta["ns"] = model_meta.get("ns")
+ prop_meta["prefix"] = model_meta.get("prefix")
+
+ if prop_meta.get("unwrapped", False):
+ # unwrapped could only set on array
+ wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta))
+ elif prop_meta.get("text", False):
+ # text could only set on primitive type
+ wrapped_element.text = _get_primitive_type_value(v)
+ elif prop_meta.get("attribute", False):
+ xml_name = prop_meta.get("name", k)
+ if prop_meta.get("ns"):
+ ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore
+ xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore
+ # attribute should be primitive type
+ wrapped_element.set(xml_name, _get_primitive_type_value(v))
+ else:
+ # other wrapped prop element
+ wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta))
+ return wrapped_element
+ if isinstance(o, list):
+ return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore
+ if isinstance(o, dict):
+ result = []
+ for k, v in o.items():
+ result.append(
+ _get_wrapped_element(
+ v,
+ exclude_readonly,
+ {
+ "name": k,
+ "ns": parent_meta.get("ns") if parent_meta else None,
+ "prefix": parent_meta.get("prefix") if parent_meta else None,
+ },
+ )
+ )
+ return result
+
+ # primitive case need to create element based on parent_meta
+ if parent_meta:
+ return _get_wrapped_element(
+ o,
+ exclude_readonly,
+ {
+ "name": parent_meta.get("itemsName", parent_meta.get("name")),
+ "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")),
+ "ns": parent_meta.get("itemsNs", parent_meta.get("ns")),
+ },
+ )
+
+ raise ValueError("Could not serialize value into xml: " + o)
+
+
+def _get_wrapped_element(
+ v: typing.Any,
+ exclude_readonly: bool,
+ meta: typing.Optional[typing.Dict[str, typing.Any]],
+) -> ET.Element:
+ wrapped_element = _create_xml_element(
+ meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None
+ )
+ if isinstance(v, (dict, list)):
+ wrapped_element.extend(_get_element(v, exclude_readonly, meta))
+ elif _is_model(v):
+ _get_element(v, exclude_readonly, meta, wrapped_element)
+ else:
+ wrapped_element.text = _get_primitive_type_value(v)
+ return wrapped_element
+
+
+def _get_primitive_type_value(v) -> str:
+ if v is True:
+ return "true"
+ if v is False:
+ return "false"
+ if isinstance(v, _Null):
+ return ""
+ return str(v)
+
+
+def _create_xml_element(tag, prefix=None, ns=None):
+ if prefix and ns:
+ ET.register_namespace(prefix, ns)
+ if ns:
+ return ET.Element("{" + ns + "}" + tag)
+ return ET.Element(tag)
+
+
+def _deserialize_xml(
+ deserializer: typing.Any,
+ value: str,
) -> typing.Any:
- return _RestField(name=name, type=type, is_discriminator=True)
+ element = ET.fromstring(value) # nosec
+ return _deserialize(deserializer, element)
+
+
+def _convert_element(e: ET.Element):
+ # dict case
+ if len(e.attrib) > 0 or len({child.tag for child in e}) > 1:
+ dict_result: typing.Dict[str, typing.Any] = {}
+ for child in e:
+ if dict_result.get(child.tag) is not None:
+ if isinstance(dict_result[child.tag], list):
+ dict_result[child.tag].append(_convert_element(child))
+ else:
+ dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)]
+ else:
+ dict_result[child.tag] = _convert_element(child)
+ dict_result.update(e.attrib)
+ return dict_result
+ # array case
+ if len(e) > 0:
+ array_result: typing.List[typing.Any] = []
+ for child in e:
+ array_result.append(_convert_element(child))
+ return array_result
+ # primitive case
+ return e.text
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py
index 06eb1614ceb7..462bfe7de7f9 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py
@@ -5,17 +5,23 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import JobRouterAdministrationClientOperationsMixin
-from ._patch import JobRouterClientOperationsMixin
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+from ._operations import JobRouterAdministrationClientOperationsMixin # type: ignore
+from ._operations import JobRouterClientOperationsMixin # type: ignore
from ._patch import __all__ as _patch_all
-from ._patch import * # pylint: disable=unused-wildcard-import
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"JobRouterAdministrationClientOperationsMixin",
"JobRouterClientOperationsMixin",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py
index b6747c961542..347154018be1 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py
@@ -1,4 +1,4 @@
-# pylint: disable=too-many-lines,too-many-statements
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -10,7 +10,7 @@
from io import IOBase
import json
import sys
-from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
+from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core import MatchConditions
@@ -21,6 +21,8 @@
ResourceModifiedError,
ResourceNotFoundError,
ResourceNotModifiedError,
+ StreamClosedError,
+ StreamConsumedError,
map_error,
)
from azure.core.paging import ItemPaged
@@ -37,7 +39,7 @@
if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
else:
- from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
+ from typing import MutableMapping # type: ignore
JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
@@ -140,9 +142,12 @@ def build_job_router_administration_list_distribution_policies_request( # pylin
def build_job_router_administration_delete_distribution_policy_request( # pylint: disable=name-too-long
distribution_policy_id: str, **kwargs: Any
) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/distributionPolicies/{distributionPolicyId}"
path_format_arguments = {
@@ -154,7 +159,10 @@ def build_job_router_administration_delete_distribution_policy_request( # pylin
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_administration_upsert_classification_policy_request( # pylint: disable=name-too-long
@@ -251,9 +259,12 @@ def build_job_router_administration_list_classification_policies_request( # pyl
def build_job_router_administration_delete_classification_policy_request( # pylint: disable=name-too-long
classification_policy_id: str, **kwargs: Any
) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/classificationPolicies/{classificationPolicyId}"
path_format_arguments = {
@@ -265,7 +276,10 @@ def build_job_router_administration_delete_classification_policy_request( # pyl
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_administration_upsert_exception_policy_request( # pylint: disable=name-too-long
@@ -362,9 +376,12 @@ def build_job_router_administration_list_exception_policies_request( # pylint:
def build_job_router_administration_delete_exception_policy_request( # pylint: disable=name-too-long
exception_policy_id: str, **kwargs: Any
) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/exceptionPolicies/{exceptionPolicyId}"
path_format_arguments = {
@@ -376,7 +393,10 @@ def build_job_router_administration_delete_exception_policy_request( # pylint:
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_administration_upsert_queue_request( # pylint: disable=name-too-long
@@ -473,9 +493,12 @@ def build_job_router_administration_list_queues_request( # pylint: disable=name
def build_job_router_administration_delete_queue_request( # pylint: disable=name-too-long
queue_id: str, **kwargs: Any
) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/queues/{queueId}"
path_format_arguments = {
@@ -487,7 +510,10 @@ def build_job_router_administration_delete_queue_request( # pylint: disable=nam
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_upsert_job_request(
@@ -557,9 +583,12 @@ def build_job_router_get_job_request(job_id: str, **kwargs: Any) -> HttpRequest:
def build_job_router_delete_job_request(job_id: str, **kwargs: Any) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/jobs/{jobId}"
path_format_arguments = {
@@ -571,7 +600,10 @@ def build_job_router_delete_job_request(job_id: str, **kwargs: Any) -> HttpReque
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_reclassify_job_request(job_id: str, **kwargs: Any) -> HttpRequest:
@@ -594,9 +626,9 @@ def build_job_router_reclassify_job_request(job_id: str, **kwargs: Any) -> HttpR
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -621,9 +653,9 @@ def build_job_router_cancel_job_request(job_id: str, **kwargs: Any) -> HttpReque
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -649,9 +681,9 @@ def build_job_router_complete_job_request(job_id: str, assignment_id: str, **kwa
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -677,9 +709,9 @@ def build_job_router_close_job_request(job_id: str, assignment_id: str, **kwargs
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -776,9 +808,9 @@ def build_job_router_unassign_job_request(job_id: str, assignment_id: str, **kwa
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -833,9 +865,9 @@ def build_job_router_decline_job_offer_request( # pylint: disable=name-too-long
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
# Construct headers
- _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
if content_type is not None:
_headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str")
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs)
@@ -933,9 +965,12 @@ def build_job_router_get_worker_request(worker_id: str, **kwargs: Any) -> HttpRe
def build_job_router_delete_worker_request(worker_id: str, **kwargs: Any) -> HttpRequest:
+ _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview"))
+ accept = _headers.pop("Accept", "application/json")
+
# Construct URL
_url = "/routing/workers/{workerId}"
path_format_arguments = {
@@ -947,7 +982,10 @@ def build_job_router_delete_worker_request(worker_id: str, **kwargs: Any) -> Htt
# Construct parameters
_params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")
- return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs)
+ # Construct headers
+ _headers["Accept"] = _SERIALIZER.header("accept", accept, "str")
+
+ return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs)
def build_job_router_list_workers_request(
@@ -990,6 +1028,7 @@ def build_job_router_list_workers_request(
class JobRouterAdministrationClientOperationsMixin( # pylint: disable=name-too-long
JobRouterAdministrationClientMixinABC
):
+
@overload
def upsert_distribution_policy(
self,
@@ -1002,7 +1041,6 @@ def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -1025,243 +1063,6 @@ def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@overload
@@ -1276,7 +1077,6 @@ def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -1299,162 +1099,6 @@ def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@overload
@@ -1469,7 +1113,6 @@ def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -1492,162 +1135,6 @@ def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@distributed_trace
@@ -1661,7 +1148,6 @@ def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -1682,245 +1168,8 @@ def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1959,7 +1208,7 @@ def upsert_distribution_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1972,28 +1221,21 @@ def upsert_distribution_policy(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.DistributionPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.DistributionPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.DistributionPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -2002,7 +1244,6 @@ def upsert_distribution_policy(
@distributed_trace
def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Retrieves an existing distribution policy by Id.
Retrieves an existing distribution policy by Id.
@@ -2012,93 +1253,8 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) ->
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2118,7 +1274,7 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) ->
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2131,7 +1287,10 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) ->
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2149,10 +1308,8 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) ->
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.DistributionPolicy"]:
- # pylint: disable=line-too-long
+ def list_distribution_policies(self, **kwargs: Any) -> Iterable["_models.DistributionPolicy"]:
"""Retrieves existing distribution policies.
Retrieves existing distribution policies.
@@ -2160,91 +1317,6 @@ def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.Distri
:return: An iterator like instance of DistributionPolicy
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.DistributionPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -2252,7 +1324,7 @@ def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.Distri
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.DistributionPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2270,9 +1342,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2290,9 +1360,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2315,8 +1383,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2338,7 +1404,7 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2358,7 +1424,7 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2370,8 +1436,6 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2390,7 +1454,6 @@ def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -2413,192 +1476,6 @@ def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@overload
@@ -2613,7 +1490,6 @@ def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -2636,126 +1512,6 @@ def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@overload
@@ -2770,7 +1526,6 @@ def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -2793,126 +1548,6 @@ def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@distributed_trace
@@ -2926,7 +1561,6 @@ def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -2947,194 +1581,8 @@ def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3173,7 +1621,7 @@ def upsert_classification_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3186,28 +1634,21 @@ def upsert_classification_policy(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ClassificationPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ClassificationPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.ClassificationPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -3216,7 +1657,6 @@ def upsert_classification_policy(
@distributed_trace
def get_classification_policy(self, classification_policy_id: str, **kwargs: Any) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Retrieves an existing classification policy by Id.
Retrieves an existing classification policy by Id.
@@ -3226,78 +1666,8 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3317,7 +1687,7 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3330,7 +1700,10 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3348,10 +1721,8 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.ClassificationPolicy"]:
- # pylint: disable=line-too-long
+ def list_classification_policies(self, **kwargs: Any) -> Iterable["_models.ClassificationPolicy"]:
"""Retrieves existing classification policies.
Retrieves existing classification policies.
@@ -3360,76 +1731,6 @@ def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.Clas
:rtype:
~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -3437,7 +1738,7 @@ def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.Clas
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.ClassificationPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3455,9 +1756,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3475,9 +1774,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3500,8 +1797,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3523,7 +1818,7 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3543,7 +1838,7 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3555,8 +1850,6 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3597,41 +1890,6 @@ def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@overload
@@ -3668,25 +1926,6 @@ def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@overload
@@ -3723,25 +1962,6 @@ def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@distributed_trace
@@ -3775,43 +1995,8 @@ def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3850,7 +2035,7 @@ def upsert_exception_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3863,28 +2048,21 @@ def upsert_exception_policy(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ExceptionPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ExceptionPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.ExceptionPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -3902,27 +2080,8 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3942,7 +2101,7 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3955,7 +2114,10 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3973,9 +2135,8 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.ExceptionPolicy"]:
+ def list_exception_policies(self, **kwargs: Any) -> Iterable["_models.ExceptionPolicy"]:
"""Retrieves existing exception policies.
Retrieves existing exception policies.
@@ -3983,25 +2144,6 @@ def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.Exception
:return: An iterator like instance of ExceptionPolicy
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -4009,7 +2151,7 @@ def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.Exception
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.ExceptionPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4027,9 +2169,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4047,9 +2187,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4072,8 +2210,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4095,7 +2231,7 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4115,7 +2251,7 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4127,8 +2263,6 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4147,7 +2281,6 @@ def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -4168,43 +2301,8 @@ def upsert_queue(
:keyword match_condition: The match condition to use upon the etag. Default value is None.
:paramtype match_condition: ~azure.core.MatchConditions
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
+ :rtype: ~azure.communication.jobrouter.models.RouterQueue
+ :raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
@@ -4219,7 +2317,6 @@ def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -4242,25 +2339,6 @@ def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
@overload
@@ -4275,7 +2353,6 @@ def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -4298,25 +2375,6 @@ def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
@distributed_trace
@@ -4330,7 +2388,6 @@ def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -4351,43 +2408,8 @@ def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4426,7 +2448,7 @@ def upsert_queue(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4439,28 +2461,21 @@ def upsert_queue(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterQueue, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterQueue, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterQueue, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -4469,7 +2484,6 @@ def upsert_queue(
@distributed_trace
def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Retrieves an existing queue by Id.
Retrieves an existing queue by Id.
@@ -4479,27 +2493,8 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4519,7 +2514,7 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4532,7 +2527,10 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4550,10 +2548,8 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]:
- # pylint: disable=line-too-long
+ def list_queues(self, **kwargs: Any) -> Iterable["_models.RouterQueue"]:
"""Retrieves existing queues.
Retrieves existing queues.
@@ -4561,25 +2557,6 @@ def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]:
:return: An iterator like instance of RouterQueue
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterQueue]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -4587,7 +2564,7 @@ def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]:
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterQueue]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4605,9 +2582,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4625,9 +2600,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4650,8 +2623,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4671,7 +2642,7 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4691,7 +2662,7 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4703,8 +2674,6 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4713,6 +2682,7 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable
class JobRouterClientOperationsMixin(JobRouterClientMixinABC):
+
@overload
def upsert_job(
self,
@@ -4725,7 +2695,6 @@ def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -4748,256 +2717,6 @@ def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -5012,7 +2731,6 @@ def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -5035,142 +2753,6 @@ def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -5185,7 +2767,6 @@ def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -5208,142 +2789,6 @@ def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@distributed_trace
@@ -5357,7 +2802,6 @@ def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -5378,258 +2822,8 @@ def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5668,7 +2862,7 @@ def upsert_job(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5681,28 +2875,21 @@ def upsert_job(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterJob, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterJob, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterJob, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -5711,7 +2898,6 @@ def upsert_job(
@distributed_trace
def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Retrieves an existing job by Id.
Retrieves an existing job by Id.
@@ -5721,126 +2907,8 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5860,7 +2928,7 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5873,7 +2941,10 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -5903,7 +2974,7 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5923,7 +2994,7 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5935,8 +3006,6 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -5944,35 +3013,30 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc
return cls(pipeline_response, None, {}) # type: ignore
@overload
- def _reclassify_job( # pylint: disable=protected-access
+ def _reclassify_job(
self,
job_id: str,
options: Optional[_models._models.ReclassifyJobOptions] = None,
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
-
+ ) -> _models.ReclassifyJobResult: ...
@overload
- def _reclassify_job( # pylint: disable=protected-access
+ def _reclassify_job(
self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
-
+ ) -> _models.ReclassifyJobResult: ...
@overload
- def _reclassify_job( # pylint: disable=protected-access
+ def _reclassify_job(
self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
+ ) -> _models.ReclassifyJobResult: ...
@distributed_trace
- def _reclassify_job( # pylint: disable=protected-access
+ def _reclassify_job(
self,
job_id: str,
options: Optional[Union[_models._models.ReclassifyJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
+ ) -> _models.ReclassifyJobResult:
"""Reclassify a job.
Reclassify a job.
@@ -5981,18 +3045,13 @@ def _reclassify_job( # pylint: disable=protected-access
:type job_id: str
:param options: Request object for reclassifying a job. Is one of the following types:
ReclassifyJobOptions, JSON, IO[bytes] Default value is None.
- :type options: ~azure.communication.jobrouter.models.ReclassifyJobOptions or JSON or IO[bytes]
+ :type options: ~azure.communication.jobrouter.models._models.ReclassifyJobOptions or JSON or
+ IO[bytes]
:return: ReclassifyJobResult. The ReclassifyJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ReclassifyJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {}
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6004,7 +3063,7 @@ def _reclassify_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.ReclassifyJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.ReclassifyJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -6025,7 +3084,7 @@ def _reclassify_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6038,16 +3097,17 @@ def _reclassify_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.ReclassifyJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.ReclassifyJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -6055,33 +3115,27 @@ def _reclassify_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- def _cancel_job( # pylint: disable=protected-access
+ def _cancel_job(
self,
job_id: str,
options: Optional[_models.CancelJobOptions] = None,
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
-
+ ) -> _models.CancelJobResult: ...
@overload
- def _cancel_job( # pylint: disable=protected-access
+ def _cancel_job(
self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
-
+ ) -> _models.CancelJobResult: ...
@overload
- def _cancel_job( # pylint: disable=protected-access
+ def _cancel_job(
self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
+ ) -> _models.CancelJobResult: ...
@distributed_trace
- def _cancel_job( # pylint: disable=protected-access
+ def _cancel_job(
self, job_id: str, options: Optional[Union[_models.CancelJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any
- ) -> _models._models.CancelJobResult:
- # pylint: disable=line-too-long
+ ) -> _models.CancelJobResult:
"""Submits request to cancel an existing job by Id while supplying free-form cancellation reason.
Submits request to cancel an existing job by Id while supplying free-form cancellation reason.
@@ -6094,20 +3148,8 @@ def _cancel_job( # pylint: disable=protected-access
:return: CancelJobResult. The CancelJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CancelJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "dispositionCode": "str", # Optional. Indicates the outcome of a job,
- populate this field with your own custom values. If not provided, default value
- of "Cancelled" is set.
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6119,7 +3161,7 @@ def _cancel_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CancelJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CancelJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -6140,7 +3182,7 @@ def _cancel_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6153,16 +3195,17 @@ def _cancel_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CancelJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CancelJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -6170,7 +3213,7 @@ def _cancel_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- def _complete_job( # pylint: disable=protected-access
+ def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -6178,11 +3221,9 @@ def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
-
+ ) -> _models.CompleteJobResult: ...
@overload
- def _complete_job( # pylint: disable=protected-access
+ def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -6190,11 +3231,9 @@ def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
-
+ ) -> _models.CompleteJobResult: ...
@overload
- def _complete_job( # pylint: disable=protected-access
+ def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -6202,17 +3241,16 @@ def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
+ ) -> _models.CompleteJobResult: ...
@distributed_trace
- def _complete_job( # pylint: disable=protected-access
+ def _complete_job(
self,
job_id: str,
assignment_id: str,
options: Optional[Union[_models.CompleteJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
+ ) -> _models.CompleteJobResult:
"""Completes an assigned job.
Completes an assigned job.
@@ -6227,17 +3265,8 @@ def _complete_job( # pylint: disable=protected-access
:return: CompleteJobResult. The CompleteJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CompleteJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6249,7 +3278,7 @@ def _complete_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CompleteJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CompleteJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -6271,7 +3300,7 @@ def _complete_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6284,16 +3313,17 @@ def _complete_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CompleteJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CompleteJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -6301,7 +3331,7 @@ def _complete_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- def _close_job( # pylint: disable=protected-access
+ def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -6309,11 +3339,9 @@ def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
-
+ ) -> _models.CloseJobResult: ...
@overload
- def _close_job( # pylint: disable=protected-access
+ def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -6321,11 +3349,9 @@ def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
-
+ ) -> _models.CloseJobResult: ...
@overload
- def _close_job( # pylint: disable=protected-access
+ def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -6333,18 +3359,16 @@ def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
+ ) -> _models.CloseJobResult: ...
@distributed_trace
- def _close_job( # pylint: disable=protected-access
+ def _close_job(
self,
job_id: str,
assignment_id: str,
options: Optional[Union[_models.CloseJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- # pylint: disable=line-too-long
+ ) -> _models.CloseJobResult:
"""Closes a completed job.
Closes a completed job.
@@ -6359,23 +3383,8 @@ def _close_job( # pylint: disable=protected-access
:return: CloseJobResult. The CloseJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CloseJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "closeAt": "2020-02-20 00:00:00", # Optional. If not provided, worker
- capacity is released immediately along with a JobClosedEvent notification. If
- provided, worker capacity is released along with a JobClosedEvent notification at
- a future time in UTC.
- "dispositionCode": "str", # Optional. Indicates the outcome of a job,
- populate this field with your own custom values.
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6387,7 +3396,7 @@ def _close_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CloseJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CloseJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -6409,7 +3418,7 @@ def _close_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6422,23 +3431,23 @@ def _close_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CloseJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CloseJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
def list_jobs(
self,
@@ -6450,8 +3459,7 @@ def list_jobs(
scheduled_before: Optional[datetime.datetime] = None,
scheduled_after: Optional[datetime.datetime] = None,
**kwargs: Any
- ) -> ItemPaged["_models.RouterJob"]:
- # pylint: disable=line-too-long
+ ) -> Iterable["_models.RouterJob"]:
"""Retrieves list of jobs based on filter parameters.
Retrieves list of jobs based on filter parameters.
@@ -6477,124 +3485,6 @@ def list_jobs(
:return: An iterator like instance of RouterJob
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterJob]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -6602,7 +3492,7 @@ def list_jobs(
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterJob]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6626,9 +3516,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6646,9 +3534,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6671,8 +3557,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6692,23 +3576,8 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos
MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJobPositionDetails
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "estimatedWaitTimeMinutes": 0.0, # Estimated wait time of the job rounded up
- to the nearest minute. Required.
- "jobId": "str", # Id of the job these details are about. Required.
- "position": 0, # Position of the job in question within that queue.
- Required.
- "queueId": "str", # Id of the queue this job is enqueued in. Required.
- "queueLength": 0 # Length of the queue: total number of enqueued jobs.
- Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6728,7 +3597,7 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6741,7 +3610,10 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6765,7 +3637,6 @@ def unassign_job(
content_type: str = "application/json",
**kwargs: Any
) -> _models.UnassignJobResult:
- # pylint: disable=line-too-long
"""Unassign a job.
Unassign a job.
@@ -6782,22 +3653,6 @@ def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "suspendMatching": bool # Optional. If SuspendMatching is true, then a job
- is not queued for re-matching with a worker.
- }
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@overload
@@ -6826,16 +3681,6 @@ def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@overload
@@ -6864,16 +3709,6 @@ def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@distributed_trace
@@ -6884,7 +3719,6 @@ def unassign_job(
options: Optional[Union[_models.UnassignJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
) -> _models.UnassignJobResult:
- # pylint: disable=line-too-long
"""Unassign a job.
Unassign a job.
@@ -6899,24 +3733,8 @@ def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "suspendMatching": bool # Optional. If SuspendMatching is true, then a job
- is not queued for re-matching with a worker.
- }
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6950,7 +3768,7 @@ def unassign_job(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6963,7 +3781,10 @@ def unassign_job(
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6992,20 +3813,8 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod
:return: AcceptJobOfferResult. The AcceptJobOfferResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.AcceptJobOfferResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "assignmentId": "str", # Id of job assignment that assigns a worker that has
- accepted an offer to a job. Required.
- "jobId": "str", # Id of the job assigned. Required.
- "workerId": "str" # Id of the worker that has been assigned this job.
- Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7026,7 +3835,7 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7039,7 +3848,10 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -7054,7 +3866,7 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod
return deserialized # type: ignore
@overload
- def _decline_job_offer( # pylint: disable=protected-access
+ def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -7062,11 +3874,9 @@ def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
-
+ ) -> _models.DeclineJobOfferResult: ...
@overload
- def _decline_job_offer( # pylint: disable=protected-access
+ def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -7074,11 +3884,9 @@ def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
-
+ ) -> _models.DeclineJobOfferResult: ...
@overload
- def _decline_job_offer( # pylint: disable=protected-access
+ def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -7086,18 +3894,16 @@ def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
+ ) -> _models.DeclineJobOfferResult: ...
@distributed_trace
- def _decline_job_offer( # pylint: disable=protected-access
+ def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
options: Optional[Union[_models.DeclineJobOfferOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- # pylint: disable=line-too-long
+ ) -> _models.DeclineJobOfferResult:
"""Declines an offer to work on a job.
Declines an offer to work on a job.
@@ -7113,21 +3919,8 @@ def _decline_job_offer( # pylint: disable=protected-access
:return: DeclineJobOfferResult. The DeclineJobOfferResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DeclineJobOfferResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "retryOfferAt": "2020-02-20 00:00:00" # Optional. If the RetryOfferAt is not
- provided, then this job will not be offered again to the worker who declined this
- job unless the worker is de-registered and re-registered. If a RetryOfferAt time
- is provided, then the job will be re-matched to eligible workers at the retry
- time in UTC. The worker that declined the job will also be eligible for the job
- at that time.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7139,9 +3932,7 @@ def _decline_job_offer( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.DeclineJobOfferResult] = kwargs.pop( # pylint: disable=protected-access
- "cls", None
- )
+ cls: ClsType[_models.DeclineJobOfferResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -7163,7 +3954,7 @@ def _decline_job_offer( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7176,16 +3967,17 @@ def _decline_job_offer( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.DeclineJobOfferResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.DeclineJobOfferResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -7194,7 +3986,6 @@ def _decline_job_offer( # pylint: disable=protected-access
@distributed_trace
def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQueueStatistics:
- # pylint: disable=line-too-long
"""Retrieves a queue's statistics.
Retrieves a queue's statistics.
@@ -7204,23 +3995,8 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu
:return: RouterQueueStatistics. The RouterQueueStatistics is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueueStatistics
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "length": 0, # Length of the queue: total number of enqueued jobs. Required.
- "queueId": "str", # Id of the queue these details are about. Required.
- "estimatedWaitTimeMinutes": {
- "str": 0.0 # Optional. The estimated wait time of this queue rounded
- up to the nearest minute, grouped by job priority.
- },
- "longestJobWaitTimeMinutes": 0.0 # Optional. The wait time of the job that
- has been enqueued in this queue for the longest.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7240,7 +4016,7 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7253,7 +4029,10 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -7279,7 +4058,6 @@ def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -7302,133 +4080,6 @@ def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -7443,7 +4094,6 @@ def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -7466,71 +4116,6 @@ def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -7545,7 +4130,6 @@ def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -7568,71 +4152,6 @@ def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@distributed_trace
@@ -7646,7 +4165,6 @@ def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -7667,135 +4185,8 @@ def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7834,7 +4225,7 @@ def upsert_worker(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7847,28 +4238,21 @@ def upsert_worker(
if response.status_code not in [200, 201]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterWorker, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterWorker, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterWorker, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -7877,7 +4261,6 @@ def upsert_worker(
@distributed_trace
def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Retrieves an existing worker by Id.
Retrieves an existing worker by Id.
@@ -7887,73 +4270,8 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker:
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7973,7 +4291,7 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker:
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7986,7 +4304,10 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker:
if response.status_code not in [200]:
if _stream:
- response.read() # Load the body in memory and close the socket
+ try:
+ response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -8016,7 +4337,7 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -8036,7 +4357,7 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -8048,15 +4369,12 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if cls:
return cls(pipeline_response, None, {}) # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
def list_workers(
self,
@@ -8066,8 +4384,7 @@ def list_workers(
queue_id: Optional[str] = None,
has_capacity: Optional[bool] = None,
**kwargs: Any
- ) -> ItemPaged["_models.RouterWorker"]:
- # pylint: disable=line-too-long
+ ) -> Iterable["_models.RouterWorker"]:
"""Retrieves existing workers.
Retrieves existing workers.
@@ -8089,71 +4406,6 @@ def list_workers(
:return: An iterator like instance of RouterWorker
:rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterWorker]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -8161,7 +4413,7 @@ def list_workers(
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterWorker]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -8183,9 +4435,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -8203,9 +4453,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -8228,8 +4476,6 @@ def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py
index a42a1a9ecbaf..f7dd32510333 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py
@@ -6,2130 +6,9 @@
Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-import sys
-import datetime
-from typing import (
- List,
- Any,
- Optional,
- Dict,
- Union,
- overload,
- IO,
- Literal,
-)
-from azure.core import MatchConditions
-from azure.core.paging import ItemPaged
-from azure.core.tracing.decorator import distributed_trace
-from .. import models as _models
-from ._operations import (
- JobRouterClientOperationsMixin as JobRouterClientOperationsMixinGenerated,
- JobRouterAdministrationClientOperationsMixin as JobRouterAdministrationClientOperationsMixinGenerated,
-)
-from .._model_base import _deserialize_datetime as _convert_str_to_datetime # pylint:disable=protected-access
+from typing import List
-if sys.version_info >= (3, 9):
- from collections.abc import MutableMapping
-else:
- from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
-JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
-
-
-class JobRouterAdministrationClientOperationsMixin(
- JobRouterAdministrationClientOperationsMixinGenerated
-): # pylint:disable=too-many-lines,line-too-long,name-too-long
- # region ExceptionPolicy
- @overload
- def upsert_exception_policy( # pylint: disable=arguments-differ
- self,
- exception_policy_id: str,
- *,
- exception_rules: Optional[List[_models.ExceptionRule]],
- name: Optional[str],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Update an exception policy.
-
- :param str exception_policy_id: Id of the exception policy.
-
- :keyword exception_rules: (Optional) A dictionary collection of exception rules on the exception
- policy. Key is the Id of each exception rule.
- :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ExceptionPolicy
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops.py
- :start-after: [START update_exception_policy]
- :end-before: [END update_exception_policy]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to update an exception policy
- """
-
- @overload
- def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: _models.ExceptionPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.ExceptionPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_exception_policy( # pylint: disable=docstring-missing-param
- self, exception_policy_id: str, *args: Union[_models.ExceptionPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Update an exception policy.
-
- :param str exception_policy_id: Id of the exception policy.
-
- :keyword exception_rules: (Optional) A dictionary collection of exception rules on the exception
- policy. Key is the Id of each exception rule.
- :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ExceptionPolicy
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops.py
- :start-after: [START update_exception_policy]
- :end-before: [END update_exception_policy]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to update an exception policy
- """
- if not exception_policy_id:
- raise ValueError("exception_policy_id cannot be None.")
-
- exception_policy: Union[_models.ExceptionPolicy, JSON, IO[bytes]] = _models.ExceptionPolicy()
- if len(args) == 1:
- exception_policy = args[0]
-
- patch = exception_policy
- if isinstance(exception_policy, _models.ExceptionPolicy):
- patch = _models.ExceptionPolicy(
- name=kwargs.pop("name", exception_policy.name),
- exception_rules=kwargs.pop("exception_rules", exception_policy.exception_rules),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_exception_policy(
- exception_policy_id=exception_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_exception_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> ItemPaged[_models.ExceptionPolicy]:
- """Retrieves existing exception policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of ExceptionPolicy
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops.py
- :start-after: [START list_exception_policies]
- :end-before: [END list_exception_policies]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to list exception policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops.py
- :start-after: [START list_exception_policies_batched]
- :end-before: [END list_exception_policies_batched]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to list exception policies in batches
- """
- return super().list_exception_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion ExceptionPolicy
-
- # region DistributionPolicy
- @overload
- def upsert_distribution_policy( # pylint: disable=arguments-differ
- self,
- distribution_policy_id: str,
- *,
- name: Optional[str] = None,
- offer_expires_after_seconds: Optional[float] = None,
- mode: Optional[Union[_models.BestWorkerMode, _models.LongestIdleMode, _models.RoundRobinMode]] = None,
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Update a distribution policy.
-
- :param str distribution_policy_id: Id of the distribution policy.
-
- :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy
- will be governed by the offer time to live.
-
- :keyword mode: Specified distribution mode
- :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode,
- ~azure.communication.jobrouter.models.LongestIdleMode,
- ~azure.communication.jobrouter.models.RoundRobinMode]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of DistributionPolicy
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops.py
- :start-after: [START update_distribution_policy]
- :end-before: [END update_distribution_policy]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a distribution policy
- """
-
- @overload
- def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: _models.DistributionPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.DistributionPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_distribution_policy( # pylint: disable=docstring-missing-param,docstring-should-be-keyword
- self, distribution_policy_id: str, *args: Union[_models.DistributionPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Update a distribution policy.
-
- :param str distribution_policy_id: Id of the distribution policy.
-
- :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy
- will be governed by the offer time to live.
-
- :keyword mode: Specified distribution mode
- :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode,
- ~azure.communication.jobrouter.models.LongestIdleMode,
- ~azure.communication.jobrouter.models.RoundRobinMode]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of DistributionPolicy
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops.py
- :start-after: [START update_distribution_policy]
- :end-before: [END update_distribution_policy]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a distribution policy
- """
- if not distribution_policy_id:
- raise ValueError("distribution_policy_id cannot be None.")
-
- distribution_policy: Union[_models.DistributionPolicy, JSON, IO[bytes]] = _models.DistributionPolicy()
- if len(args) == 1:
- distribution_policy = args[0]
-
- patch = distribution_policy
- if isinstance(distribution_policy, _models.DistributionPolicy):
- patch = _models.DistributionPolicy(
- name=kwargs.pop("name", distribution_policy.name),
- offer_expires_after_seconds=kwargs.pop(
- "offer_expires_after_seconds", distribution_policy.offer_expires_after_seconds
- ),
- mode=kwargs.pop("mode", distribution_policy.mode),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_distribution_policy(
- distribution_policy_id=distribution_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_distribution_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> ItemPaged[_models.DistributionPolicy]:
- """Retrieves existing distribution policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of DistributionPolicy
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.DistributionPolicy]
- :raises: ~azure.core.exceptions.HttpResponseError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops.py
- :start-after: [START list_distribution_policies]
- :end-before: [END list_distribution_policies]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list distribution policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops.py
- :start-after: [START list_distribution_policies_batched]
- :end-before: [END list_distribution_policies_batched]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list distribution policies in batches
- """
- return super().list_distribution_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion DistributionPolicy
-
- # region Queue
- @overload
- def upsert_queue( # pylint: disable=arguments-differ
- self,
- queue_id: str,
- *,
- distribution_policy_id: Optional[str],
- name: Optional[str],
- labels: Optional[Dict[str, Union[int, float, str, bool]]],
- exception_policy_id: Optional[str],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Update a job queue
-
- :param str queue_id: Id of the queue.
-
- :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine
- how a job is distributed to workers.
-
- :keyword Optional[str] name: The name of this queue.
-
- :keyword labels: A set of key/value pairs that are
- identifying attributes used by the rules engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]]
-
- :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various
- job escalation rules.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterQueue
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops.py
- :start-after: [START update_queue]
- :end-before: [END update_queue]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a queue
- """
-
- @overload
- def upsert_queue(
- self,
- queue_id: str,
- resource: _models.RouterQueue,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterQueue
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_queue(
- self,
- queue_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_queue(
- self,
- queue_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_queue( # pylint: disable=docstring-missing-param
- self, queue_id: str, *args: Union[_models.RouterQueue, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.RouterQueue:
- """Update a job queue
-
- :param str queue_id: Id of the queue.
-
- :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine
- how a job is distributed to workers.
-
- :keyword Optional[str] name: The name of this queue.
-
- :keyword labels: A set of key/value pairs that are
- identifying attributes used by the rules engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]]
-
- :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various
- job escalation rules.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterQueue
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops.py
- :start-after: [START update_queue]
- :end-before: [END update_queue]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a queue
- """
- if not queue_id:
- raise ValueError("queue_id cannot be None.")
-
- queue: Union[_models.RouterQueue, JSON, IO[bytes]] = _models.RouterQueue()
- if len(args) == 1:
- queue = args[0]
-
- patch = queue
- if isinstance(queue, _models.RouterQueue):
- patch = _models.RouterQueue(
- name=kwargs.pop("name", queue.name),
- distribution_policy_id=kwargs.pop("distribution_policy_id", queue.distribution_policy_id),
- labels=kwargs.pop("labels", queue.labels),
- exception_policy_id=kwargs.pop("exception_policy_id", queue.exception_policy_id),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_queue(
- queue_id=queue_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_queues(self, *, results_per_page: Optional[int] = None, **kwargs: Any) -> ItemPaged[_models.RouterQueue]:
- """Retrieves existing queues.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterQueueItem
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterQueueItem]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops.py
- :start-after: [START list_queues]
- :end-before: [END list_queues]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list queues
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops.py
- :start-after: [START list_queues_batched]
- :end-before: [END list_queues_batched]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list queues in batches
- """
- return super().list_queues(maxpagesize=results_per_page, **kwargs)
-
- # endregion Queue
-
- # region ClassificationPolicy
- @overload
- def upsert_classification_policy( # pylint: disable=arguments-differ
- self,
- classification_policy_id: str,
- *,
- name: Optional[str],
- fallback_queue_id: Optional[str],
- queue_selectors: Optional[
- List[
- Union[
- _models.StaticQueueSelectorAttachment,
- _models.ConditionalQueueSelectorAttachment,
- _models.RuleEngineQueueSelectorAttachment,
- _models.PassThroughQueueSelectorAttachment,
- _models.WeightedAllocationQueueSelectorAttachment,
- ]
- ]
- ], # pylint: disable=line-too-long
- prioritization_rule: Optional[
- Union[
- _models.StaticRouterRule,
- _models.ExpressionRouterRule,
- _models.FunctionRouterRule,
- _models.WebhookRouterRule,
- ]
- ], # pylint: disable=line-too-long
- worker_selectors: Optional[
- List[
- Union[
- _models.StaticWorkerSelectorAttachment,
- _models.ConditionalWorkerSelectorAttachment,
- _models.RuleEngineWorkerSelectorAttachment,
- _models.PassThroughWorkerSelectorAttachment,
- _models.WeightedAllocationWorkerSelectorAttachment,
- ]
- ]
- ], # pylint: disable=line-too-long
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Update a classification policy
-
- :param str classification_policy_id: Id of the classification policy.
-
- :keyword Optional[str] name: Friendly name of this policy.
-
- :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match.
- :paramtype fallback_queue_id: Optional[str]
-
- :keyword queue_selector_attachments: The queue selectors to resolve a queue for a given job.
- :paramtype queue_selector_attachments: Optional[List[Union
- ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]]
-
- :keyword prioritization_rule: The rule to determine a priority score for a given job.
- :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule,
- ~azure.communication.jobrouter.models.ExpressionRouterRule,
- ~azure.communication.jobrouter.models.FunctionRouterRule,
- ~azure.communication.jobrouter.models.WebhookRouterRule]]
-
- :keyword worker_selector_attachments: The worker label selectors to attach to a given job.
- :paramtype worker_selector_attachments: Optional[List[Union[
- ~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ClassificationPolicy
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops.py
- :start-after: [START update_classification_policy]
- :end-before: [END update_classification_policy]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a classification policy
- """
-
- @overload
- def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: _models.ClassificationPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.ClassificationPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_classification_policy( # pylint: disable=docstring-missing-param
- self, classification_policy_id: str, *args: Union[_models.ClassificationPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Update a classification policy
-
- :param str classification_policy_id: Id of the classification policy.
-
- :keyword Optional[str] name: Friendly name of this policy.
-
- :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match.
- :paramtype fallback_queue_id: Optional[str]
-
- :keyword queue_selector_attachments: The queue selectors to resolve a queue for a given job.
- :paramtype queue_selector_attachments: Optional[List[Union
- ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]]
-
- :keyword prioritization_rule: The rule to determine a priority score for a given job.
- :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule,
- ~azure.communication.jobrouter.models.ExpressionRouterRule,
- ~azure.communication.jobrouter.models.FunctionRouterRule,
- ~azure.communication.jobrouter.models.WebhookRouterRule]]
-
- :keyword worker_selector_attachments: The worker label selectors to attach to a given job.
- :paramtype worker_selector_attachments: Optional[List[Union[
- ~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ClassificationPolicy
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops.py
- :start-after: [START update_classification_policy]
- :end-before: [END update_classification_policy]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a classification policy
- """
- if not classification_policy_id:
- raise ValueError("classification_policy_id cannot be None.")
-
- classification_policy: Union[_models.ClassificationPolicy, JSON, IO[bytes]] = _models.ClassificationPolicy()
- if len(args) == 1:
- classification_policy = args[0]
-
- patch = classification_policy
- if isinstance(classification_policy, _models.ClassificationPolicy):
- patch = _models.ClassificationPolicy(
- name=kwargs.pop("name", classification_policy.name),
- fallback_queue_id=kwargs.pop("fallback_queue_id", classification_policy.fallback_queue_id),
- queue_selector_attachments=kwargs.pop(
- "queue_selector_attachments", classification_policy.queue_selector_attachments
- ),
- prioritization_rule=kwargs.pop("prioritization_rule", classification_policy.prioritization_rule),
- worker_selector_attachments=kwargs.pop(
- "worker_selector_attachments", classification_policy.worker_selector_attachments
- ),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_classification_policy(
- classification_policy_id=classification_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_classification_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> ItemPaged[_models.ClassificationPolicy]:
- """Retrieves existing classification policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of ClassificationPolicy
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops.py
- :start-after: [START list_classification_policies]
- :end-before: [END list_classification_policies]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list classification policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops.py
- :start-after: [START list_classification_policies_batched]
- :end-before: [END list_classification_policies_batched]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list classification policies in batches
- """
- return super().list_classification_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion ClassificationPolicy
-
-
-class JobRouterClientOperationsMixin(JobRouterClientOperationsMixinGenerated):
- # region Worker
- @overload
- def upsert_worker( # pylint: disable=arguments-differ
- self,
- worker_id: str,
- *,
- queues: Optional[List[str]],
- capacity: Optional[int],
- labels: Optional[Dict[str, Union[int, float, str, bool]]],
- tags: Optional[Dict[str, Union[int, float, str, bool]]],
- channels: Optional[List[_models.RouterChannel]],
- available_for_offers: Optional[bool],
- max_concurrent_offers: Optional[int],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Update a router worker.
-
- :param str worker_id: Id of the worker.
-
- :keyword queue_assignments: The queue(s) that this worker can receive work from.
- :paramtype queue_assignments: Optional[Dict[str, Union[~collections.abc.MutableMapping[str, Any], None]]]
-
- :keyword total_capacity: The total capacity score this worker has to manage multiple concurrent
- jobs.
- :paramtype total_capacity: Optional[int]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword channel_configurations: The channel(s) this worker can handle and their impact on the
- workers capacity.
- :paramtype channel_configurations: Optional[Dict[str,
- ~azure.communication.jobrouter.models.ChannelConfiguration]]
-
- :keyword available_for_offers: A flag indicating this worker is open to receive offers or not.
- :paramtype available_for_offers: Optional[bool]
-
- :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new
- offers at a time.
- :paramtype max_concurrent_offers: Optional[int]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterWorker
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START update_worker]
- :end-before: [END update_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START register_worker]
- :end-before: [END register_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START deregister_worker]
- :end-before: [END deregister_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to de-register a worker
- """
-
- @overload
- def upsert_worker(
- self,
- worker_id: str,
- resource: _models.RouterWorker,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterWorker
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_worker(
- self,
- worker_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_worker(
- self,
- worker_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_worker( # pylint: disable=docstring-missing-param
- self, worker_id: str, *args: Union[_models.RouterWorker, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.RouterWorker:
- """Update a router worker.
-
- :param str worker_id: Id of the worker.
-
- :keyword queue_assignments: The queue(s) that this worker can receive work from.
- :paramtype queue_assignments: Optional[Dict[str, Union[~collections.abc.MutableMapping[str, Any], None]]]
-
- :keyword total_capacity: The total capacity score this worker has to manage multiple concurrent
- jobs.
- :paramtype total_capacity: Optional[int]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword channel_configurations: The channel(s) this worker can handle and their impact on the
- workers capacity.
- :paramtype channel_configurations: Optional[Dict[str,
- ~azure.communication.jobrouter.models.ChannelConfiguration]]
-
- :keyword available_for_offers: A flag indicating this worker is open to receive offers or not.
- :paramtype available_for_offers: Optional[bool]
-
- :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new
- offers at a time.
- :paramtype max_concurrent_offers: Optional[int]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterWorker
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START update_worker]
- :end-before: [END update_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START register_worker]
- :end-before: [END register_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START deregister_worker]
- :end-before: [END deregister_worker]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to de-register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START create_worker_w_limit_concurrent_offers]
- :end-before: [END create_worker_w_limit_concurrent_offers]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to create a worker with concurrent offer limit
- """
- if not worker_id:
- raise ValueError("worker_id cannot be None.")
-
- router_worker: Union[_models.RouterWorker, JSON, IO[bytes]] = _models.RouterWorker()
- if len(args) == 1:
- router_worker = args[0]
-
- patch = router_worker
- if isinstance(router_worker, _models.RouterWorker):
- patch = _models.RouterWorker(
- queues=kwargs.pop("queues", router_worker.queues),
- capacity=kwargs.pop("capacity", router_worker.capacity),
- labels=kwargs.pop("labels", router_worker.labels),
- tags=kwargs.pop("tags", router_worker.tags),
- channels=kwargs.pop("channels", router_worker.channels),
- available_for_offers=kwargs.pop("available_for_offers", router_worker.available_for_offers),
- max_concurrent_offers=kwargs.pop("max_concurrent_offers", router_worker.max_concurrent_offers),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_worker(
- worker_id=worker_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_workers(
- self,
- *,
- state: Optional[Union[str, _models.RouterWorkerState, Literal["all"]]] = "all",
- channel_id: Optional[str] = None,
- queue_id: Optional[str] = None,
- has_capacity: Optional[bool] = None,
- results_per_page: Optional[int] = None,
- **kwargs: Any
- ) -> ItemPaged[_models.RouterWorker]:
- """Retrieves existing workers.
-
- :keyword state: If specified, select workers by worker status. Default value is "all".
- Accepted value(s): active, draining, inactive, all
- :paramtype state: Optional[Union[str, ~azure.communication.jobrouter.models.RouterWorkerState, Literal["all"]]]
-
- :keyword channel_id: If specified, select workers who have a channel configuration
- with this channel. Default value is None.
- :paramtype channel_id: Optional[str]
-
- :keyword queue_id: If specified, select workers who are assigned to this queue.
- Default value is None.
- :paramtype queue_id: Optional[str]
-
- :keyword has_capacity: If set to true, select only workers who have capacity for the
- channel specified by ``channelId`` or for any channel
- :paramtype has_capacity: Optional[bool]
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterWorkerItem
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterWorkerItem]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START list_workers]
- :end-before: [END list_workers]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve workers
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START list_workers_batched]
- :end-before: [END list_workers_batched]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve workers in batches
- """
- return super().list_workers(
- maxpagesize=results_per_page,
- state=state,
- channel_id=channel_id,
- queue_id=queue_id,
- has_capacity=has_capacity,
- **kwargs
- )
-
- # endregion Worker
-
- # region Job
- @overload
- def upsert_job( # pylint: disable=arguments-differ
- self,
- job_id: str,
- *,
- channel_reference: Optional[str],
- channel_id: Optional[str],
- classification_policy_id: Optional[str],
- queue_id: Optional[str],
- priority: Optional[int],
- disposition_code: Optional[str],
- requested_worker_selectors: Optional[List[_models.RouterWorkerSelector]],
- labels: Optional[Dict[str, Union[int, float, str, bool, None]]],
- tags: Optional[Dict[str, Union[int, float, str, bool, None]]],
- notes: Optional[Dict[datetime.datetime, str]],
- matching_mode: Optional[_models.JobMatchingMode],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Update a job.
-
- :param str job_id: Id of the job.
-
- :keyword channel_reference: Reference to an external parent context, eg. call ID.
- :paramtype channel_reference: Optional[str]
-
- :keyword channel_id: The channel identifier. eg. voice, chat, etc.
- :paramtype channel_id: Optional[str]
-
- :keyword classification_policy_id: The Id of the Classification policy used for classifying a
- job.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword queue_id: The Id of the Queue that this job is queued to.
- :paramtype queue_id: Optional[str]
-
- :keyword priority: The priority of this job.
- :paramtype priority: Optional[int]
-
- :keyword disposition_code: Reason code for cancelled or closed jobs.
- :paramtype disposition_code: Optional[str]
-
- :keyword requested_worker_selectors: A collection of manually specified label selectors, which
- a worker must satisfy in order to process this job.
- :paramtype requested_worker_selectors: Optional[List[
- ~azure.communication.jobrouter.models.RouterWorkerSelector]]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this job.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword notes: Notes attached to a job, sorted by timestamp.
- :paramtype notes: Optional[Dict[~datetime.datetime, str]]
-
- :keyword matching_mode: If set, determines how a job will be matched
- :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterJob
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START update_job]
- :end-before: [END update_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a job
- """
-
- @overload
- def upsert_job(
- self,
- job_id: str,
- resource: _models.RouterJob,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterJob
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_job(
- self,
- job_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- def upsert_job(
- self,
- job_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- def upsert_job( # pylint: disable=docstring-missing-param
- self,
- job_id: str,
- *args: Union[_models.RouterJob, JSON, IO[bytes]],
- **kwargs: Any
- ) -> _models.RouterJob:
- """Update a job.
-
- :param str job_id: Id of the job.
-
- :keyword channel_reference: Reference to an external parent context, eg. call ID.
- :paramtype channel_reference: Optional[str]
-
- :keyword channel_id: The channel identifier. eg. voice, chat, etc.
- :paramtype channel_id: Optional[str]
-
- :keyword classification_policy_id: The Id of the Classification policy used for classifying a
- job.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword queue_id: The Id of the Queue that this job is queued to.
- :paramtype queue_id: Optional[str]
-
- :keyword priority: The priority of this job.
- :paramtype priority: Optional[int]
-
- :keyword disposition_code: Reason code for cancelled or closed jobs.
- :paramtype disposition_code: Optional[str]
-
- :keyword requested_worker_selectors: A collection of manually specified label selectors, which
- a worker must satisfy in order to process this job.
- :paramtype requested_worker_selectors: Optional[List[
- ~azure.communication.jobrouter.models.RouterWorkerSelector]]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this job.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword notes: Notes attached to a job, sorted by timestamp.
- :paramtype notes: Optional[Dict[~datetime.datetime, str]]
-
- :keyword matching_mode: If set, determines how a job will be matched
- :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterJob
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START update_job]
- :end-before: [END update_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- router_job: Union[_models.RouterJob, JSON, IO[bytes]] = _models.RouterJob()
- if len(args) == 1:
- router_job = args[0]
-
- patch = router_job
- if isinstance(router_job, _models.RouterJob):
- patch = _models.RouterJob(
- channel_reference=kwargs.pop("channel_reference", router_job.channel_reference),
- channel_id=kwargs.pop("channel_id", router_job.channel_id),
- classification_policy_id=kwargs.pop("classification_policy_id", router_job.classification_policy_id),
- queue_id=kwargs.pop("queue_id", router_job.queue_id),
- priority=kwargs.pop("priority", router_job.priority),
- disposition_code=kwargs.pop("disposition_code", router_job.disposition_code),
- requested_worker_selectors=kwargs.pop(
- "requested_worker_selectors", router_job.requested_worker_selectors
- ),
- labels=kwargs.pop("labels", router_job.labels),
- tags=kwargs.pop("tags", router_job.tags),
- notes=kwargs.pop("notes", router_job.notes),
- matching_mode=kwargs.pop("matching_mode", router_job.matching_mode),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return super().upsert_job(
- job_id=job_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_jobs(
- self,
- *,
- status: Optional[Union[str, _models.RouterJobStatus, Literal["all", "active"]]] = "all",
- channel_id: Optional[str] = None,
- queue_id: Optional[str] = None,
- classification_policy_id: Optional[str] = None,
- scheduled_before: Optional[Union[str, datetime.datetime]] = None,
- scheduled_after: Optional[Union[str, datetime.datetime]] = None,
- results_per_page: Optional[int] = None,
- **kwargs: Any
- ) -> ItemPaged[_models.RouterJob]:
- """Retrieves list of jobs based on filter parameters.
-
- :keyword status: If specified, filter jobs by status. Default value is "all".
- Accepted value(s): pendingClassification, queued, assigned, completed, closed, cancelled,
- classificationFailed, active, all
- :paramtype status: Optional[Union[str,
- ~azure.communication.jobrouter.models.RouterJobStatus, Literal["all","active"]]]
-
- :keyword channel_id: If specified, filter jobs by channel. Default value is None.
- :paramtype channel_id: Optional[str]
-
- :keyword queue_id: If specified, filter jobs by queue. Default value is None.
- :paramtype queue_id: Optional[str]
-
- :keyword classification_policy_id: If specified, filter jobs by classificationPolicy. Default value is None.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword scheduled_before: If specified, filter on jobs that was scheduled before or
- at given timestamp. Range: (-Inf, scheduledBefore]. Default value is None.
- :paramtype scheduled_before: Optional[Union[str, ~datetime.datetime]]
-
- :keyword scheduled_after: If specified, filter on jobs that was scheduled at or
- after given value. Range: [scheduledAfter, +Inf). Default value is None.
- :paramtype scheduled_after: Optional[Union[str, ~datetime.datetime]]
-
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterJobItem
- :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterJobItem]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START list_jobs]
- :end-before: [END list_jobs]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve jobs
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START list_jobs_batched]
- :end-before: [END list_jobs_batched]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve jobs in batches
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START list_scheduled_jobs]
- :end-before: [END list_scheduled_jobs]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve scheduled jobs
- """
- if scheduled_before is not None and isinstance(scheduled_before, str):
- scheduled_before = _convert_str_to_datetime(scheduled_before)
-
- if scheduled_after is not None and isinstance(scheduled_after, str):
- scheduled_after = _convert_str_to_datetime(scheduled_after)
-
- return super().list_jobs(
- maxpagesize=results_per_page,
- status=status,
- channel_id=channel_id,
- queue_id=queue_id,
- classification_policy_id=classification_policy_id,
- scheduled_before=scheduled_before,
- scheduled_after=scheduled_after,
- **kwargs
- )
-
- @distributed_trace
- def reclassify_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=arguments-differ,arguments-renamed
- """Reclassify a job.
-
- :param str job_id: Id of the job.
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START reclassify_job]
- :end-before: [END reclassify_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to re-classify a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- super()._reclassify_job(job_id=job_id, options={}, **kwargs)
-
- @distributed_trace
- def cancel_job(
- self, job_id: str, options: Optional[Union[_models._models.CancelJobOptions, JSON, IO]] = None, **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Closes a completed job.
-
- :param str job_id: Id of the job.
-
- :param options: Request model for cancelling job. Is one of the following types:
- CancelJobOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CancelJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START cancel_job]
- :end-before: [END cancel_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to cancel a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- super()._cancel_job(job_id=job_id, options=options, **kwargs)
-
- @distributed_trace
- def complete_job(
- self,
- job_id: str,
- assignment_id: str,
- options: Optional[Union[_models._models.CompleteJobOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Completes an assigned job.
-
- :param str job_id: Id of the job.
-
- :param assignment_id: The Id of the job assignment. Required.
- :type assignment_id: str
-
- :param options: Request model for completing job. Is one of the following types:
- CompleteJobOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CompleteJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START complete_job]
- :end-before: [END complete_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to complete a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- if not assignment_id:
- raise ValueError("assignment_id cannot be None.")
-
- super()._complete_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs)
-
- @distributed_trace
- def close_job(
- self,
- job_id: str,
- assignment_id: str,
- options: Optional[Union[_models._models.CloseJobOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Closes a completed job.
-
- :param str job_id: Id of the job.
-
- :param assignment_id: The Id of the job assignment. Required.
- :type assignment_id: str
- :param options: Request model for closing job. Is one of the following types: CloseJobOptions,
- JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CloseJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START close_job]
- :end-before: [END close_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to close a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- if not assignment_id:
- raise ValueError("assignment_id cannot be None.")
-
- super()._close_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs)
-
- # endregion Job
-
- # region Offer
- @distributed_trace
- def decline_job_offer(
- self,
- worker_id: str,
- offer_id: str,
- options: Optional[Union[_models._models.DeclineJobOfferOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Declines an offer to work on a job.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param offer_id: Id of the offer. Required.
- :type offer_id: str
- :param options: Request model for declining offer. Is one of the following types:
- DeclineJobOfferOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.DeclineJobOfferOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops.py
- :start-after: [START close_job]
- :end-before: [END close_job]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to close a job
- """
- if not worker_id:
- raise ValueError("worker_id cannot be None.")
-
- if not offer_id:
- raise ValueError("offer_id cannot be None.")
-
- super()._decline_job_offer(worker_id=worker_id, offer_id=offer_id, options=options, **kwargs)
-
- # endregion Offer
-
-
-__all__: List[str] = [
- "JobRouterClientOperationsMixin",
- "JobRouterAdministrationClientOperationsMixin",
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py
index 9f503d53e0d6..f7dd32510333 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py
@@ -6,156 +6,9 @@
Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-from typing import (
- List,
- Any,
-)
-from urllib.parse import urlparse
-from azure.core.credentials import AzureKeyCredential
-from ._shared.utils import parse_connection_str
-from ._shared.policy import HMACCredentialsPolicy
-from ._client import (
- JobRouterClient as JobRouterClientGenerated,
- JobRouterAdministrationClient as JobRouterAdministrationClientGenerated,
-)
-from ._api_versions import DEFAULT_VERSION
+from typing import List
-
-class JobRouterClient(JobRouterClientGenerated):
- """A client to interact with the AzureCommunicationService JobRouter service.
-
- This client provides operations to create and update jobs, policies and workers.
-
- :param str endpoint:
- The endpoint of the Azure Communication resource.
- :param ~azure.core.credentials.AzureKeyCredential credential:
- The credentials with which to authenticate
-
- :keyword api_version: Azure Communication Job Router API version.
- Default value is "2023-11-01".
- Note that overriding this default value may result in unsupported behavior.
- """
-
- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None:
- if not credential:
- raise ValueError("credential can not be None")
-
- # TokenCredential not supported at the moment
- if hasattr(credential, "get_token"):
- raise TypeError(
- "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy"
- " for authentication".format(type(credential))
- )
-
- try:
- if not endpoint.lower().startswith("http"):
- endpoint = "https://" + endpoint
- except AttributeError:
- raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from
-
- parsed_url = urlparse(endpoint.rstrip("/"))
- if not parsed_url.netloc:
- raise ValueError("Invalid URL: {}".format(endpoint))
-
- self._endpoint = endpoint
- self._api_version = kwargs.pop("api_version", DEFAULT_VERSION)
- self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key)
- super().__init__(
- self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs
- )
-
- @classmethod
- def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterClient":
- """Create JobRouterClient from a Connection String.
-
- :param str conn_str:
- A connection string to an Azure Communication Service resource.
- :return: Instance of JobRouterClient.
- :rtype: ~azure.communication.jobrouter.JobRouterClient
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/sample_authentication.py
- :start-after: [START auth_from_connection_string]
- :end-before: [END auth_from_connection_string]
- :language: python
- :dedent: 8
- :caption: Authenticating a JobRouterClient from a connection_string
- """
- endpoint, access_key = parse_connection_str(conn_str)
- return cls(endpoint, AzureKeyCredential(access_key), **kwargs)
-
-
-class JobRouterAdministrationClient(JobRouterAdministrationClientGenerated):
- """A client to interact with the AzureCommunicationService JobRouter service.
-
- This client provides operations to create, update, list and delete the following entities: classification policy,
- exception policy, distribution policy and queue.
-
- :param str endpoint:
- The endpoint of the Azure Communication resource.
- :param ~azure.core.credentials.AzureKeyCredential credential:
- The credentials with which to authenticate
-
- :keyword api_version: Azure Communication Job Router API version. Default value is "2023-11-01".
- Note that overriding this default value may result in unsupported behavior.
- :paramtype api_version: str
- """
-
- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> "None":
- if not credential:
- raise ValueError("credential can not be None")
-
- # TokenCredential not supported at the moment
- if hasattr(credential, "get_token"):
- raise TypeError(
- "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy"
- " for authentication".format(type(credential))
- )
-
- try:
- if not endpoint.lower().startswith("http"):
- endpoint = "https://" + endpoint
- except AttributeError:
- raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from
-
- parsed_url = urlparse(endpoint.rstrip("/"))
- if not parsed_url.netloc:
- raise ValueError("Invalid URL: {}".format(endpoint))
-
- self._endpoint = endpoint
- self._api_version = kwargs.pop("api_version", DEFAULT_VERSION)
- self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key)
- super().__init__(
- self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs
- )
-
- @classmethod
- def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterAdministrationClient":
- """Create JobRouterClient from a Connection String.
-
- :param str conn_str:
- A connection string to an Azure Communication Service resource.
- :return: Instance of JobRouterAdministrationClient.
- :rtype: ~azure.communication.jobrouter.JobRouterAdministrationClient
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/sample_authentication.py
- :start-after: [START admin_auth_from_connection_string]
- :end-before: [END admin_auth_from_connection_string]
- :language: python
- :dedent: 8
- :caption: Authenticating a JobRouterAdministrationClient from a connection_string
- """
- endpoint, access_key = parse_connection_str(conn_str)
- return cls(endpoint, AzureKeyCredential(access_key), **kwargs)
-
-
-__all__: List[str] = [
- "JobRouterClient",
- "JobRouterAdministrationClient",
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py
index 2f781d740827..ce17d1798ce7 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py
@@ -1,3 +1,4 @@
+# pylint: disable=too-many-lines
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -24,7 +25,6 @@
#
# --------------------------------------------------------------------------
-# pylint: skip-file
# pyright: reportUnnecessaryTypeIgnoreComment=false
from base64 import b64decode, b64encode
@@ -52,7 +52,6 @@
MutableMapping,
Type,
List,
- Mapping,
)
try:
@@ -91,6 +90,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type:
:param data: Input, could be bytes or stream (will be decoded with UTF8) or text
:type data: str or bytes or IO
:param str content_type: The content type.
+ :return: The deserialized data.
+ :rtype: object
"""
if hasattr(data, "read"):
# Assume a stream
@@ -112,7 +113,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type:
try:
return json.loads(data_as_str)
except ValueError as err:
- raise DeserializationError("JSON is invalid: {}".format(err), err)
+ raise DeserializationError("JSON is invalid: {}".format(err), err) from err
elif "xml" in (content_type or []):
try:
@@ -144,6 +145,8 @@ def _json_attemp(data):
# context otherwise.
_LOGGER.critical("Wasn't XML not JSON, failing")
raise DeserializationError("XML is invalid") from err
+ elif content_type.startswith("text/"):
+ return data_as_str
raise DeserializationError("Cannot deserialize content-type: {}".format(content_type))
@classmethod
@@ -153,6 +156,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]],
Use bytes and headers to NOT use any requests/aiohttp or whatever
specific implementation.
Headers will tested for "content-type"
+
+ :param bytes body_bytes: The body of the response.
+ :param dict headers: The headers of the response.
+ :returns: The deserialized data.
+ :rtype: object
"""
# Try to use content-type from headers if available
content_type = None
@@ -182,15 +190,30 @@ class UTC(datetime.tzinfo):
"""Time Zone info for handling UTC"""
def utcoffset(self, dt):
- """UTF offset for UTC is 0."""
+ """UTF offset for UTC is 0.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The offset
+ :rtype: datetime.timedelta
+ """
return datetime.timedelta(0)
def tzname(self, dt):
- """Timestamp representation."""
+ """Timestamp representation.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The timestamp representation
+ :rtype: str
+ """
return "Z"
def dst(self, dt):
- """No daylight saving for UTC."""
+ """No daylight saving for UTC.
+
+ :param datetime.datetime dt: The datetime
+ :returns: The daylight saving time
+ :rtype: datetime.timedelta
+ """
return datetime.timedelta(hours=1)
@@ -204,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore
:param datetime.timedelta offset: offset in timedelta format
"""
- def __init__(self, offset):
+ def __init__(self, offset) -> None:
self.__offset = offset
def utcoffset(self, dt):
@@ -233,24 +256,26 @@ def __getinitargs__(self):
_FLATTEN = re.compile(r"(? None:
self.additional_properties: Optional[Dict[str, Any]] = {}
- for k in kwargs:
+ for k in kwargs: # pylint: disable=consider-using-dict-items
if k not in self._attribute_map:
_LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__)
elif k in self._validation and self._validation[k].get("readonly", False):
@@ -298,13 +330,23 @@ def __init__(self, **kwargs: Any) -> None:
setattr(self, k, kwargs[k])
def __eq__(self, other: Any) -> bool:
- """Compare objects by comparing all attributes."""
+ """Compare objects by comparing all attributes.
+
+ :param object other: The object to compare
+ :returns: True if objects are equal
+ :rtype: bool
+ """
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
return False
def __ne__(self, other: Any) -> bool:
- """Compare objects by comparing all attributes."""
+ """Compare objects by comparing all attributes.
+
+ :param object other: The object to compare
+ :returns: True if objects are not equal
+ :rtype: bool
+ """
return not self.__eq__(other)
def __str__(self) -> str:
@@ -324,7 +366,11 @@ def is_xml_model(cls) -> bool:
@classmethod
def _create_xml_node(cls):
- """Create XML node."""
+ """Create XML node.
+
+ :returns: The XML node
+ :rtype: xml.etree.ElementTree.Element
+ """
try:
xml_map = cls._xml_map # type: ignore
except AttributeError:
@@ -344,7 +390,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON:
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
- return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
+ self, keep_readonly=keep_readonly, **kwargs
+ )
def as_dict(
self,
@@ -378,12 +426,15 @@ def my_key_transformer(key, attr_desc, value):
If you want XML serialization, you can pass the kwargs is_xml=True.
+ :param bool keep_readonly: If you want to serialize the readonly attributes
:param function key_transformer: A key transformer function.
:returns: A dict JSON compatible object
:rtype: dict
"""
serializer = Serializer(self._infer_class_models())
- return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore
+ return serializer._serialize( # type: ignore # pylint: disable=protected-access
+ self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs
+ )
@classmethod
def _infer_class_models(cls):
@@ -393,7 +444,7 @@ def _infer_class_models(cls):
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
if cls.__name__ not in client_models:
raise ValueError("Not Autorest generated code")
- except Exception:
+ except Exception: # pylint: disable=broad-exception-caught
# Assume it's not Autorest generated (tests?). Add ourselves as dependencies.
client_models = {cls.__name__: cls}
return client_models
@@ -406,6 +457,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
+ :rtype: ModelType
"""
deserializer = Deserializer(cls._infer_class_models())
return deserializer(cls.__name__, data, content_type=content_type) # type: ignore
@@ -424,9 +476,11 @@ def from_dict(
and last_rest_key_case_insensitive_extractor)
:param dict data: A dict using RestAPI structure
+ :param function key_extractors: A key extractor function.
:param str content_type: JSON by default, set application/xml if XML.
:returns: An instance of this model
:raises: DeserializationError if something went wrong
+ :rtype: ModelType
"""
deserializer = Deserializer(cls._infer_class_models())
deserializer.key_extractors = ( # type: ignore
@@ -446,21 +500,25 @@ def _flatten_subtype(cls, key, objects):
return {}
result = dict(cls._subtype_map[key])
for valuetype in cls._subtype_map[key].values():
- result.update(objects[valuetype]._flatten_subtype(key, objects))
+ result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access
return result
@classmethod
def _classify(cls, response, objects):
"""Check the class _subtype_map for any child classes.
We want to ignore any inherited _subtype_maps.
- Remove the polymorphic key from the initial data.
+
+ :param dict response: The initial data
+ :param dict objects: The class objects
+ :returns: The class to be used
+ :rtype: class
"""
for subtype_key in cls.__dict__.get("_subtype_map", {}).keys():
subtype_value = None
if not isinstance(response, ET.Element):
rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1]
- subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None)
+ subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None)
else:
subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response)
if subtype_value:
@@ -499,11 +557,13 @@ def _decode_attribute_map_key(key):
inside the received data.
:param str key: A key string from the generated code
+ :returns: The decoded key
+ :rtype: str
"""
return key.replace("\\.", ".")
-class Serializer(object):
+class Serializer(object): # pylint: disable=too-many-public-methods
"""Request object model serializer."""
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
@@ -538,7 +598,7 @@ class Serializer(object):
"multiple": lambda x, y: x % y != 0,
}
- def __init__(self, classes: Optional[Mapping[str, type]] = None):
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
self.serialize_type = {
"iso-8601": Serializer.serialize_iso,
"rfc-1123": Serializer.serialize_rfc,
@@ -558,13 +618,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None):
self.key_transformer = full_restapi_key_transformer
self.client_side_validation = True
- def _serialize(self, target_obj, data_type=None, **kwargs):
+ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals
+ self, target_obj, data_type=None, **kwargs
+ ):
"""Serialize data into a string according to type.
- :param target_obj: The data to be serialized.
+ :param object target_obj: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str, dict
:raises: SerializationError if serialization fails.
+ :returns: The serialized data.
"""
key_transformer = kwargs.get("key_transformer", self.key_transformer)
keep_readonly = kwargs.get("keep_readonly", False)
@@ -590,12 +653,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
serialized = {}
if is_xml_model_serialization:
- serialized = target_obj._create_xml_node()
+ serialized = target_obj._create_xml_node() # pylint: disable=protected-access
try:
- attributes = target_obj._attribute_map
+ attributes = target_obj._attribute_map # pylint: disable=protected-access
for attr, attr_desc in attributes.items():
attr_name = attr
- if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False):
+ if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access
+ attr_name, {}
+ ).get("readonly", False):
continue
if attr_name == "additional_properties" and attr_desc["key"] == "":
@@ -631,7 +696,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
if isinstance(new_attr, list):
serialized.extend(new_attr) # type: ignore
elif isinstance(new_attr, ET.Element):
- # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
+ # If the down XML has no XML/Name,
+ # we MUST replace the tag with the local tag. But keeping the namespaces.
if "name" not in getattr(orig_attr, "_xml_map", {}):
splitted_tag = new_attr.tag.split("}")
if len(splitted_tag) == 2: # Namespace
@@ -662,17 +728,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs):
except (AttributeError, KeyError, TypeError) as err:
msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj))
raise SerializationError(msg) from err
- else:
- return serialized
+ return serialized
def body(self, data, data_type, **kwargs):
"""Serialize data intended for a request body.
- :param data: The data to be serialized.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: dict
:raises: SerializationError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized request body
"""
# Just in case this is a dict
@@ -701,7 +767,7 @@ def body(self, data, data_type, **kwargs):
attribute_key_case_insensitive_extractor,
last_rest_key_case_insensitive_extractor,
]
- data = deserializer._deserialize(data_type, data)
+ data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access
except DeserializationError as err:
raise SerializationError("Unable to build a model: " + str(err)) from err
@@ -710,9 +776,11 @@ def body(self, data, data_type, **kwargs):
def url(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL path.
- :param data: The data to be serialized.
+ :param str name: The name of the URL path parameter.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
+ :returns: The serialized URL path
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
"""
@@ -726,21 +794,20 @@ def url(self, name, data, data_type, **kwargs):
output = output.replace("{", quote("{")).replace("}", quote("}"))
else:
output = quote(str(output), safe="")
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return output
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return output
def query(self, name, data, data_type, **kwargs):
"""Serialize data intended for a URL query.
- :param data: The data to be serialized.
+ :param str name: The name of the query parameter.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
- :keyword bool skip_quote: Whether to skip quote the serialized result.
- Defaults to False.
:rtype: str, list
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized query parameter
"""
try:
# Treat the list aside, since we don't want to encode the div separator
@@ -757,19 +824,20 @@ def query(self, name, data, data_type, **kwargs):
output = str(output)
else:
output = quote(str(output), safe="")
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return str(output)
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return str(output)
def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.
- :param data: The data to be serialized.
+ :param str name: The name of the header.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if data is None
+ :returns: The serialized header
"""
try:
if data_type in ["[str]"]:
@@ -778,21 +846,20 @@ def header(self, name, data, data_type, **kwargs):
output = self.serialize_data(data, data_type, **kwargs)
if data_type == "bool":
output = json.dumps(output)
- except SerializationError:
- raise TypeError("{} must be type {}.".format(name, data_type))
- else:
- return str(output)
+ except SerializationError as exc:
+ raise TypeError("{} must be type {}.".format(name, data_type)) from exc
+ return str(output)
def serialize_data(self, data, data_type, **kwargs):
"""Serialize generic data according to supplied data type.
- :param data: The data to be serialized.
+ :param object data: The data to be serialized.
:param str data_type: The type to be serialized from.
- :param bool required: Whether it's essential that the data not be
- empty or None
:raises: AttributeError if required data is None.
:raises: ValueError if data is None
:raises: SerializationError if serialization fails.
+ :returns: The serialized data.
+ :rtype: str, int, float, bool, dict, list
"""
if data is None:
raise ValueError("No value for given attribute")
@@ -803,7 +870,7 @@ def serialize_data(self, data, data_type, **kwargs):
if data_type in self.basic_types.values():
return self.serialize_basic(data, data_type, **kwargs)
- elif data_type in self.serialize_type:
+ if data_type in self.serialize_type:
return self.serialize_type[data_type](data, **kwargs)
# If dependencies is empty, try with current data class
@@ -819,11 +886,10 @@ def serialize_data(self, data, data_type, **kwargs):
except (ValueError, TypeError) as err:
msg = "Unable to serialize value: {!r} as type: {!r}."
raise SerializationError(msg.format(data, data_type)) from err
- else:
- return self._serialize(data, **kwargs)
+ return self._serialize(data, **kwargs)
@classmethod
- def _get_custom_serializers(cls, data_type, **kwargs):
+ def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements
custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type)
if custom_serializer:
return custom_serializer
@@ -839,23 +905,26 @@ def serialize_basic(cls, data, data_type, **kwargs):
- basic_types_serializers dict[str, callable] : If set, use the callable as serializer
- is_xml bool : If set, use xml_basic_types_serializers
- :param data: Object to be serialized.
+ :param obj data: Object to be serialized.
:param str data_type: Type of object in the iterable.
+ :rtype: str, int, float, bool
+ :return: serialized object
"""
custom_serializer = cls._get_custom_serializers(data_type, **kwargs)
if custom_serializer:
return custom_serializer(data)
if data_type == "str":
return cls.serialize_unicode(data)
- return eval(data_type)(data) # nosec
+ return eval(data_type)(data) # nosec # pylint: disable=eval-used
@classmethod
def serialize_unicode(cls, data):
"""Special handling for serializing unicode strings in Py2.
Encode to UTF-8 if unicode, otherwise handle as a str.
- :param data: Object to be serialized.
+ :param str data: Object to be serialized.
:rtype: str
+ :return: serialized object
"""
try: # If I received an enum, return its value
return data.value
@@ -869,8 +938,7 @@ def serialize_unicode(cls, data):
return data
except NameError:
return str(data)
- else:
- return str(data)
+ return str(data)
def serialize_iter(self, data, iter_type, div=None, **kwargs):
"""Serialize iterable.
@@ -880,15 +948,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs):
serialization_ctxt['type'] should be same as data_type.
- is_xml bool : If set, serialize as XML
- :param list attr: Object to be serialized.
+ :param list data: Object to be serialized.
:param str iter_type: Type of object in the iterable.
- :param bool required: Whether the objects in the iterable must
- not be None or empty.
:param str div: If set, this str will be used to combine the elements
in the iterable into a combined string. Default is 'None'.
- :keyword bool do_quote: Whether to quote the serialized result of each iterable element.
Defaults to False.
:rtype: list, str
+ :return: serialized iterable
"""
if isinstance(data, str):
raise SerializationError("Refuse str type as a valid iter type.")
@@ -943,9 +1009,8 @@ def serialize_dict(self, attr, dict_type, **kwargs):
:param dict attr: Object to be serialized.
:param str dict_type: Type of object in the dictionary.
- :param bool required: Whether the objects in the dictionary must
- not be None or empty.
:rtype: dict
+ :return: serialized dictionary
"""
serialization_ctxt = kwargs.get("serialization_ctxt", {})
serialized = {}
@@ -969,7 +1034,7 @@ def serialize_dict(self, attr, dict_type, **kwargs):
return serialized
- def serialize_object(self, attr, **kwargs):
+ def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
"""Serialize a generic object.
This will be handled as a dictionary. If object passed in is not
a basic type (str, int, float, dict, list) it will simply be
@@ -977,6 +1042,7 @@ def serialize_object(self, attr, **kwargs):
:param dict attr: Object to be serialized.
:rtype: dict or str
+ :return: serialized object
"""
if attr is None:
return None
@@ -1001,7 +1067,7 @@ def serialize_object(self, attr, **kwargs):
return self.serialize_decimal(attr)
# If it's a model or I know this dependency, serialize as a Model
- elif obj_type in self.dependencies.values() or isinstance(attr, Model):
+ if obj_type in self.dependencies.values() or isinstance(attr, Model):
return self._serialize(attr)
if obj_type == dict:
@@ -1032,56 +1098,61 @@ def serialize_enum(attr, enum_obj=None):
try:
enum_obj(result) # type: ignore
return result
- except ValueError:
+ except ValueError as exc:
for enum_value in enum_obj: # type: ignore
if enum_value.value.lower() == str(attr).lower():
return enum_value.value
error = "{!r} is not valid value for enum {!r}"
- raise SerializationError(error.format(attr, enum_obj))
+ raise SerializationError(error.format(attr, enum_obj)) from exc
@staticmethod
- def serialize_bytearray(attr, **kwargs):
+ def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize bytearray into base-64 string.
- :param attr: Object to be serialized.
+ :param str attr: Object to be serialized.
:rtype: str
+ :return: serialized base64
"""
return b64encode(attr).decode()
@staticmethod
- def serialize_base64(attr, **kwargs):
+ def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize str into base-64 string.
- :param attr: Object to be serialized.
+ :param str attr: Object to be serialized.
:rtype: str
+ :return: serialized base64
"""
encoded = b64encode(attr).decode("ascii")
return encoded.strip("=").replace("+", "-").replace("/", "_")
@staticmethod
- def serialize_decimal(attr, **kwargs):
+ def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Decimal object to float.
- :param attr: Object to be serialized.
+ :param decimal attr: Object to be serialized.
:rtype: float
+ :return: serialized decimal
"""
return float(attr)
@staticmethod
- def serialize_long(attr, **kwargs):
+ def serialize_long(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize long (Py2) or int (Py3).
- :param attr: Object to be serialized.
+ :param int attr: Object to be serialized.
:rtype: int/long
+ :return: serialized long
"""
return _long_type(attr)
@staticmethod
- def serialize_date(attr, **kwargs):
+ def serialize_date(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Date object into ISO-8601 formatted string.
:param Date attr: Object to be serialized.
:rtype: str
+ :return: serialized date
"""
if isinstance(attr, str):
attr = isodate.parse_date(attr)
@@ -1089,11 +1160,12 @@ def serialize_date(attr, **kwargs):
return t
@staticmethod
- def serialize_time(attr, **kwargs):
+ def serialize_time(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Time object into ISO-8601 formatted string.
:param datetime.time attr: Object to be serialized.
:rtype: str
+ :return: serialized time
"""
if isinstance(attr, str):
attr = isodate.parse_time(attr)
@@ -1103,30 +1175,32 @@ def serialize_time(attr, **kwargs):
return t
@staticmethod
- def serialize_duration(attr, **kwargs):
+ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize TimeDelta object into ISO-8601 formatted string.
:param TimeDelta attr: Object to be serialized.
:rtype: str
+ :return: serialized duration
"""
if isinstance(attr, str):
attr = isodate.parse_duration(attr)
return isodate.duration_isoformat(attr)
@staticmethod
- def serialize_rfc(attr, **kwargs):
+ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into RFC-1123 formatted string.
:param Datetime attr: Object to be serialized.
:rtype: str
:raises: TypeError if format invalid.
+ :return: serialized rfc
"""
try:
if not attr.tzinfo:
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
utc = attr.utctimetuple()
- except AttributeError:
- raise TypeError("RFC1123 object must be valid Datetime object.")
+ except AttributeError as exc:
+ raise TypeError("RFC1123 object must be valid Datetime object.") from exc
return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format(
Serializer.days[utc.tm_wday],
@@ -1139,12 +1213,13 @@ def serialize_rfc(attr, **kwargs):
)
@staticmethod
- def serialize_iso(attr, **kwargs):
+ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into ISO-8601 formatted string.
:param Datetime attr: Object to be serialized.
:rtype: str
:raises: SerializationError if format invalid.
+ :return: serialized iso
"""
if isinstance(attr, str):
attr = isodate.parse_datetime(attr)
@@ -1170,13 +1245,14 @@ def serialize_iso(attr, **kwargs):
raise TypeError(msg) from err
@staticmethod
- def serialize_unix(attr, **kwargs):
+ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument
"""Serialize Datetime object into IntTime format.
This is represented as seconds.
:param Datetime attr: Object to be serialized.
:rtype: int
:raises: SerializationError if format invalid
+ :return: serialied unix
"""
if isinstance(attr, int):
return attr
@@ -1184,11 +1260,11 @@ def serialize_unix(attr, **kwargs):
if not attr.tzinfo:
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
return int(calendar.timegm(attr.utctimetuple()))
- except AttributeError:
- raise TypeError("Unix time object must be valid Datetime object.")
+ except AttributeError as exc:
+ raise TypeError("Unix time object must be valid Datetime object.") from exc
-def rest_key_extractor(attr, attr_desc, data):
+def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
key = attr_desc["key"]
working_data = data
@@ -1209,7 +1285,9 @@ def rest_key_extractor(attr, attr_desc, data):
return working_data.get(key)
-def rest_key_case_insensitive_extractor(attr, attr_desc, data):
+def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements
+ attr, attr_desc, data
+):
key = attr_desc["key"]
working_data = data
@@ -1230,17 +1308,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data):
return attribute_key_case_insensitive_extractor(key, None, working_data)
-def last_rest_key_extractor(attr, attr_desc, data):
- """Extract the attribute in "data" based on the last part of the JSON path key."""
+def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
+ """Extract the attribute in "data" based on the last part of the JSON path key.
+
+ :param str attr: The attribute to extract
+ :param dict attr_desc: The attribute description
+ :param dict data: The data to extract from
+ :rtype: object
+ :returns: The extracted attribute
+ """
key = attr_desc["key"]
dict_keys = _FLATTEN.split(key)
return attribute_key_extractor(dict_keys[-1], None, data)
-def last_rest_key_case_insensitive_extractor(attr, attr_desc, data):
+def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument
"""Extract the attribute in "data" based on the last part of the JSON path key.
This is the case insensitive version of "last_rest_key_extractor"
+ :param str attr: The attribute to extract
+ :param dict attr_desc: The attribute description
+ :param dict data: The data to extract from
+ :rtype: object
+ :returns: The extracted attribute
"""
key = attr_desc["key"]
dict_keys = _FLATTEN.split(key)
@@ -1277,7 +1367,7 @@ def _extract_name_from_internal_type(internal_type):
return xml_name
-def xml_key_extractor(attr, attr_desc, data):
+def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements
if isinstance(data, dict):
return None
@@ -1329,22 +1419,21 @@ def xml_key_extractor(attr, attr_desc, data):
if is_iter_type:
if is_wrapped:
return None # is_wrapped no node, we want None
- else:
- return [] # not wrapped, assume empty list
+ return [] # not wrapped, assume empty list
return None # Assume it's not there, maybe an optional node.
# If is_iter_type and not wrapped, return all found children
if is_iter_type:
if not is_wrapped:
return children
- else: # Iter and wrapped, should have found one node only (the wrap one)
- if len(children) != 1:
- raise DeserializationError(
- "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format(
- xml_name
- )
+ # Iter and wrapped, should have found one node only (the wrap one)
+ if len(children) != 1:
+ raise DeserializationError(
+ "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( # pylint: disable=line-too-long
+ xml_name
)
- return list(children[0]) # Might be empty list and that's ok.
+ )
+ return list(children[0]) # Might be empty list and that's ok.
# Here it's not a itertype, we should have found one element only or empty
if len(children) > 1:
@@ -1361,9 +1450,9 @@ class Deserializer(object):
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
- valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
+ valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
- def __init__(self, classes: Optional[Mapping[str, type]] = None):
+ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None:
self.deserialize_type = {
"iso-8601": Deserializer.deserialize_iso,
"rfc-1123": Deserializer.deserialize_rfc,
@@ -1401,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None):
:param str content_type: Swagger "produces" if available.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
data = self._unpack_content(response_data, content_type)
return self._deserialize(target_obj, data)
- def _deserialize(self, target_obj, data):
+ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements
"""Call the deserializer on a model.
Data needs to be already deserialized as JSON or XML ElementTree
@@ -1414,12 +1504,13 @@ def _deserialize(self, target_obj, data):
:param object data: Object to deserialize.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
# This is already a model, go recursive just in case
if hasattr(data, "_attribute_map"):
constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")]
try:
- for attr, mapconfig in data._attribute_map.items():
+ for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access
if attr in constants:
continue
value = getattr(data, attr)
@@ -1438,13 +1529,13 @@ def _deserialize(self, target_obj, data):
if isinstance(response, str):
return self.deserialize_data(data, response)
- elif isinstance(response, type) and issubclass(response, Enum):
+ if isinstance(response, type) and issubclass(response, Enum):
return self.deserialize_enum(data, response)
- if data is None:
+ if data is None or data is CoreNull:
return data
try:
- attributes = response._attribute_map # type: ignore
+ attributes = response._attribute_map # type: ignore # pylint: disable=protected-access
d_attrs = {}
for attr, attr_desc in attributes.items():
# Check empty string. If it's not empty, someone has a real "additionalProperties"...
@@ -1474,9 +1565,8 @@ def _deserialize(self, target_obj, data):
except (AttributeError, TypeError, KeyError) as err:
msg = "Unable to deserialize to object: " + class_name # type: ignore
raise DeserializationError(msg) from err
- else:
- additional_properties = self._build_additional_properties(attributes, data)
- return self._instantiate_model(response, d_attrs, additional_properties)
+ additional_properties = self._build_additional_properties(attributes, data)
+ return self._instantiate_model(response, d_attrs, additional_properties)
def _build_additional_properties(self, attribute_map, data):
if not self.additional_properties_detection:
@@ -1503,6 +1593,8 @@ def _classify_target(self, target, data):
:param str target: The target object type to deserialize to.
:param str/dict data: The response data to deserialize.
+ :return: The classified target object and its class name.
+ :rtype: tuple
"""
if target is None:
return None, None
@@ -1514,7 +1606,7 @@ def _classify_target(self, target, data):
return target, target
try:
- target = target._classify(data, self.dependencies) # type: ignore
+ target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access
except AttributeError:
pass # Target is not a Model, no classify
return target, target.__class__.__name__ # type: ignore
@@ -1529,10 +1621,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None):
:param str target_obj: The target object type to deserialize to.
:param str/dict data: The response data to deserialize.
:param str content_type: Swagger "produces" if available.
+ :return: Deserialized object.
+ :rtype: object
"""
try:
return self(target_obj, data, content_type=content_type)
- except:
+ except: # pylint: disable=bare-except
_LOGGER.debug(
"Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
)
@@ -1550,10 +1644,12 @@ def _unpack_content(raw_data, content_type=None):
If raw_data is something else, bypass all logic and return it directly.
- :param raw_data: Data to be processed.
- :param content_type: How to parse if raw_data is a string/bytes.
+ :param obj raw_data: Data to be processed.
+ :param str content_type: How to parse if raw_data is a string/bytes.
:raises JSONDecodeError: If JSON is requested and parsing is impossible.
:raises UnicodeDecodeError: If bytes is not UTF8
+ :rtype: object
+ :return: Unpacked content.
"""
# Assume this is enough to detect a Pipeline Response without importing it
context = getattr(raw_data, "context", {})
@@ -1577,14 +1673,21 @@ def _unpack_content(raw_data, content_type=None):
def _instantiate_model(self, response, attrs, additional_properties=None):
"""Instantiate a response model passing in deserialized args.
- :param response: The response model class.
- :param d_attrs: The deserialized response attributes.
+ :param Response response: The response model class.
+ :param dict attrs: The deserialized response attributes.
+ :param dict additional_properties: Additional properties to be set.
+ :rtype: Response
+ :return: The instantiated response model.
"""
if callable(response):
subtype = getattr(response, "_subtype_map", {})
try:
- readonly = [k for k, v in response._validation.items() if v.get("readonly")]
- const = [k for k, v in response._validation.items() if v.get("constant")]
+ readonly = [
+ k for k, v in response._validation.items() if v.get("readonly") # pylint: disable=protected-access
+ ]
+ const = [
+ k for k, v in response._validation.items() if v.get("constant") # pylint: disable=protected-access
+ ]
kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const}
response_obj = response(**kwargs)
for attr in readonly:
@@ -1594,7 +1697,7 @@ def _instantiate_model(self, response, attrs, additional_properties=None):
return response_obj
except TypeError as err:
msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore
- raise DeserializationError(msg + str(err))
+ raise DeserializationError(msg + str(err)) from err
else:
try:
for attr, value in attrs.items():
@@ -1603,15 +1706,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None):
except Exception as exp:
msg = "Unable to populate response model. "
msg += "Type: {}, Error: {}".format(type(response), exp)
- raise DeserializationError(msg)
+ raise DeserializationError(msg) from exp
- def deserialize_data(self, data, data_type):
+ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements
"""Process data for deserialization according to data type.
:param str data: The response string to be deserialized.
:param str data_type: The type to deserialize to.
:raises: DeserializationError if deserialization fails.
:return: Deserialized object.
+ :rtype: object
"""
if data is None:
return data
@@ -1625,7 +1729,11 @@ def deserialize_data(self, data, data_type):
if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())):
return data
- is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"]
+ is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment
+ "object",
+ "[]",
+ r"{}",
+ ]
if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text:
return None
data_val = self.deserialize_type[data_type](data)
@@ -1645,14 +1753,14 @@ def deserialize_data(self, data, data_type):
msg = "Unable to deserialize response data."
msg += " Data: {}, {}".format(data, data_type)
raise DeserializationError(msg) from err
- else:
- return self._deserialize(obj_type, data)
+ return self._deserialize(obj_type, data)
def deserialize_iter(self, attr, iter_type):
"""Deserialize an iterable.
:param list attr: Iterable to be deserialized.
:param str iter_type: The type of object in the iterable.
+ :return: Deserialized iterable.
:rtype: list
"""
if attr is None:
@@ -1669,6 +1777,7 @@ def deserialize_dict(self, attr, dict_type):
:param dict/list attr: Dictionary to be deserialized. Also accepts
a list of key, value pairs.
:param str dict_type: The object type of the items in the dictionary.
+ :return: Deserialized dictionary.
:rtype: dict
"""
if isinstance(attr, list):
@@ -1679,11 +1788,12 @@ def deserialize_dict(self, attr, dict_type):
attr = {el.tag: el.text for el in attr}
return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()}
- def deserialize_object(self, attr, **kwargs):
+ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements
"""Deserialize a generic object.
This will be handled as a dictionary.
:param dict attr: Dictionary to be deserialized.
+ :return: Deserialized object.
:rtype: dict
:raises: TypeError if non-builtin datatype encountered.
"""
@@ -1718,11 +1828,10 @@ def deserialize_object(self, attr, **kwargs):
pass
return deserialized
- else:
- error = "Cannot deserialize generic object with type: "
- raise TypeError(error + str(obj_type))
+ error = "Cannot deserialize generic object with type: "
+ raise TypeError(error + str(obj_type))
- def deserialize_basic(self, attr, data_type):
+ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements
"""Deserialize basic builtin data type from string.
Will attempt to convert to str, int, float and bool.
This function will also accept '1', '0', 'true' and 'false' as
@@ -1730,6 +1839,7 @@ def deserialize_basic(self, attr, data_type):
:param str attr: response string to be deserialized.
:param str data_type: deserialization data type.
+ :return: Deserialized basic type.
:rtype: str, int, float or bool
:raises: TypeError if string format is not valid.
"""
@@ -1741,24 +1851,23 @@ def deserialize_basic(self, attr, data_type):
if data_type == "str":
# None or '', node is empty string.
return ""
- else:
- # None or '', node with a strong type is None.
- # Don't try to model "empty bool" or "empty int"
- return None
+ # None or '', node with a strong type is None.
+ # Don't try to model "empty bool" or "empty int"
+ return None
if data_type == "bool":
if attr in [True, False, 1, 0]:
return bool(attr)
- elif isinstance(attr, str):
+ if isinstance(attr, str):
if attr.lower() in ["true", "1"]:
return True
- elif attr.lower() in ["false", "0"]:
+ if attr.lower() in ["false", "0"]:
return False
raise TypeError("Invalid boolean value: {}".format(attr))
if data_type == "str":
return self.deserialize_unicode(attr)
- return eval(data_type)(attr) # nosec
+ return eval(data_type)(attr) # nosec # pylint: disable=eval-used
@staticmethod
def deserialize_unicode(data):
@@ -1766,6 +1875,7 @@ def deserialize_unicode(data):
as a string.
:param str data: response string to be deserialized.
+ :return: Deserialized string.
:rtype: str or unicode
"""
# We might be here because we have an enum modeled as string,
@@ -1779,8 +1889,7 @@ def deserialize_unicode(data):
return data
except NameError:
return str(data)
- else:
- return str(data)
+ return str(data)
@staticmethod
def deserialize_enum(data, enum_obj):
@@ -1792,6 +1901,7 @@ def deserialize_enum(data, enum_obj):
:param str data: Response string to be deserialized. If this value is
None or invalid it will be returned as-is.
:param Enum enum_obj: Enum object to deserialize to.
+ :return: Deserialized enum object.
:rtype: Enum
"""
if isinstance(data, enum_obj) or data is None:
@@ -1802,9 +1912,9 @@ def deserialize_enum(data, enum_obj):
# Workaround. We might consider remove it in the future.
try:
return list(enum_obj.__members__.values())[data]
- except IndexError:
+ except IndexError as exc:
error = "{!r} is not a valid index for enum {!r}"
- raise DeserializationError(error.format(data, enum_obj))
+ raise DeserializationError(error.format(data, enum_obj)) from exc
try:
return enum_obj(str(data))
except ValueError:
@@ -1820,6 +1930,7 @@ def deserialize_bytearray(attr):
"""Deserialize string into bytearray.
:param str attr: response string to be deserialized.
+ :return: Deserialized bytearray
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
@@ -1832,6 +1943,7 @@ def deserialize_base64(attr):
"""Deserialize base64 encoded string into string.
:param str attr: response string to be deserialized.
+ :return: Deserialized base64 string
:rtype: bytearray
:raises: TypeError if string format invalid.
"""
@@ -1847,8 +1959,9 @@ def deserialize_decimal(attr):
"""Deserialize string into Decimal object.
:param str attr: response string to be deserialized.
- :rtype: Decimal
+ :return: Deserialized decimal
:raises: DeserializationError if string format invalid.
+ :rtype: decimal
"""
if isinstance(attr, ET.Element):
attr = attr.text
@@ -1863,6 +1976,7 @@ def deserialize_long(attr):
"""Deserialize string into long (Py2) or int (Py3).
:param str attr: response string to be deserialized.
+ :return: Deserialized int
:rtype: long or int
:raises: ValueError if string format invalid.
"""
@@ -1875,6 +1989,7 @@ def deserialize_duration(attr):
"""Deserialize ISO-8601 formatted string into TimeDelta object.
:param str attr: response string to be deserialized.
+ :return: Deserialized duration
:rtype: TimeDelta
:raises: DeserializationError if string format invalid.
"""
@@ -1885,14 +2000,14 @@ def deserialize_duration(attr):
except (ValueError, OverflowError, AttributeError) as err:
msg = "Cannot deserialize duration object."
raise DeserializationError(msg) from err
- else:
- return duration
+ return duration
@staticmethod
def deserialize_date(attr):
"""Deserialize ISO-8601 formatted string into Date object.
:param str attr: response string to be deserialized.
+ :return: Deserialized date
:rtype: Date
:raises: DeserializationError if string format invalid.
"""
@@ -1908,6 +2023,7 @@ def deserialize_time(attr):
"""Deserialize ISO-8601 formatted string into time object.
:param str attr: response string to be deserialized.
+ :return: Deserialized time
:rtype: datetime.time
:raises: DeserializationError if string format invalid.
"""
@@ -1922,6 +2038,7 @@ def deserialize_rfc(attr):
"""Deserialize RFC-1123 formatted string into Datetime object.
:param str attr: response string to be deserialized.
+ :return: Deserialized RFC datetime
:rtype: Datetime
:raises: DeserializationError if string format invalid.
"""
@@ -1937,14 +2054,14 @@ def deserialize_rfc(attr):
except ValueError as err:
msg = "Cannot deserialize to rfc datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
@staticmethod
def deserialize_iso(attr):
"""Deserialize ISO-8601 formatted string into Datetime object.
:param str attr: response string to be deserialized.
+ :return: Deserialized ISO datetime
:rtype: Datetime
:raises: DeserializationError if string format invalid.
"""
@@ -1974,8 +2091,7 @@ def deserialize_iso(attr):
except (ValueError, OverflowError, AttributeError) as err:
msg = "Cannot deserialize datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
@staticmethod
def deserialize_unix(attr):
@@ -1983,6 +2099,7 @@ def deserialize_unix(attr):
This is represented as seconds.
:param int attr: Object to be serialized.
+ :return: Deserialized datetime
:rtype: Datetime
:raises: DeserializationError if format invalid
"""
@@ -1994,5 +2111,4 @@ def deserialize_unix(attr):
except ValueError as err:
msg = "Cannot deserialize to unix datetime object."
raise DeserializationError(msg) from err
- else:
- return date_obj
+ return date_obj
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py
deleted file mode 100644
index 5b396cd202e8..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-# -------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# --------------------------------------------------------------------------
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py
deleted file mode 100644
index 8d516105d601..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# ------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# -------------------------------------------------------------------------
-
-from typing import Union
-from azure.core.credentials import TokenCredential, AzureKeyCredential
-from azure.core.credentials_async import AsyncTokenCredential
-from azure.core.pipeline.policies import (
- AsyncBearerTokenCredentialPolicy,
- BearerTokenCredentialPolicy,
-)
-from .._shared.policy import HMACCredentialsPolicy
-
-
-def get_authentication_policy(
- endpoint: str,
- credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str],
- decode_url: bool = False,
- is_async: bool = False,
-):
- # type: (...) -> Union[AsyncBearerTokenCredentialPolicy, BearerTokenCredentialPolicy, HMACCredentialsPolicy]
- """Returns the correct authentication policy based on which credential is being passed.
-
- :param endpoint: The endpoint to which we are authenticating to.
- :type endpoint: str
- :param credential: The credential we use to authenticate to the service
- :type credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str]
- :param bool decode_url: `True` if there is a need to decode the url. Default value is `False`
- :param bool is_async: For async clients there is a need to decode the url
-
- :return: Either AsyncBearerTokenCredentialPolicy or BearerTokenCredentialPolicy or HMACCredentialsPolicy
- :rtype: ~azure.core.pipeline.policies.AsyncBearerTokenCredentialPolicy or
- ~azure.core.pipeline.policies.BearerTokenCredentialPolicy or
- ~azure.communication.jobrouter.shared.policy.HMACCredentialsPolicy
- """
-
- if credential is None:
- raise ValueError("Parameter 'credential' must not be None.")
- if hasattr(credential, "get_token"):
- if is_async:
- return AsyncBearerTokenCredentialPolicy(
- credential, "https://communication.azure.com//.default" # type: ignore
- )
- return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore
- if isinstance(credential, (AzureKeyCredential, str)):
- return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url)
-
- raise TypeError(
- f"Unsupported credential: {format(type(credential))}. Use an access token string to use HMACCredentialsPolicy"
- "or a token credential from azure.identity"
- )
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py
deleted file mode 100644
index d5ad25d9cdb0..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py
+++ /dev/null
@@ -1,416 +0,0 @@
-# ------------------------------------
-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-# ------------------------------------
-from enum import Enum
-import warnings
-from typing import Mapping, Optional, Union, Any, cast
-from typing_extensions import Literal, TypedDict, Protocol, runtime_checkable
-
-from azure.core import CaseInsensitiveEnumMeta
-
-
-class DeprecatedEnumMeta(CaseInsensitiveEnumMeta):
- def __getattribute__(cls, item):
- if item.upper() == "MICROSOFT_BOT":
- warnings.warn(
- "MICROSOFT_BOT is deprecated and has been replaced by \
- MICROSOFT_TEAMS_APP identifier.",
- DeprecationWarning,
- )
- item = "MICROSOFT_TEAMS_APP"
- return super().__getattribute__(item)
-
-
-class CommunicationIdentifierKind(str, Enum, metaclass=DeprecatedEnumMeta):
- """Communication Identifier Kind.
-
- For checking yet unknown identifiers it is better to rely on the presence of the `raw_id` property,
- as new or existing distinct type identifiers always contain the `raw_id` property.
- It is not advisable to rely on the `kind` property with a value `unknown`,
- as it could become a new or existing distinct type in the future.
- """
-
- UNKNOWN = "unknown"
- COMMUNICATION_USER = "communication_user"
- PHONE_NUMBER = "phone_number"
- MICROSOFT_TEAMS_USER = "microsoft_teams_user"
- MICROSOFT_TEAMS_APP = "microsoft_teams_app"
-
-
-class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta):
- """The cloud environment that the identifier belongs to"""
-
- PUBLIC = "PUBLIC"
- DOD = "DOD"
- GCCH = "GCCH"
-
-
-@runtime_checkable
-class CommunicationIdentifier(Protocol):
- """Communication Identifier."""
-
- @property
- def raw_id(self) -> str:
- """The raw ID of the identifier."""
- ...
-
- @property
- def kind(self) -> CommunicationIdentifierKind:
- """The type of identifier."""
- ...
-
- @property
- def properties(self) -> Mapping[str, Any]:
- """The properties of the identifier."""
- ...
-
-
-PHONE_NUMBER_PREFIX = "4:"
-BOT_PREFIX = "28:"
-BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:"
-BOT_DOD_CLOUD_PREFIX = "28:dod:"
-BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:"
-BOT_GCCH_CLOUD_PREFIX = "28:gcch:"
-BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:"
-TEAMS_APP_PUBLIC_CLOUD_PREFIX = "28:orgid:"
-TEAMS_APP_DOD_CLOUD_PREFIX = "28:dod:"
-TEAMS_APP_GCCH_CLOUD_PREFIX = "28:gcch:"
-TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:"
-TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:"
-TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:"
-TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:"
-ACS_USER_PREFIX = "8:acs:"
-ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:"
-ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:"
-SPOOL_USER_PREFIX = "8:spool:"
-
-
-class CommunicationUserProperties(TypedDict):
- """Dictionary of properties for a CommunicationUserIdentifier."""
-
- id: str
- """ID of the Communication user as returned from Azure Communication Identity."""
-
-
-class CommunicationUserIdentifier:
- """Represents a user in Azure Communication Service."""
-
- kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER
- """The type of identifier."""
- properties: CommunicationUserProperties
- """The properties of the identifier."""
- raw_id: str
- """The raw ID of the identifier."""
-
- def __init__(self, id: str, **kwargs: Any) -> None:
- """
- :param str id: ID of the Communication user as returned from Azure Communication Identity.
- :keyword str raw_id: The raw ID of the identifier. If not specified, the 'id' value will be used.
- """
- self.properties = CommunicationUserProperties(id=id)
- raw_id: Optional[str] = kwargs.get("raw_id")
- self.raw_id = raw_id if raw_id is not None else id
-
- def __eq__(self, other):
- try:
- if other.raw_id:
- return self.raw_id == other.raw_id
- return self.raw_id == other.properties["id"]
- except Exception: # pylint: disable=broad-except
- return False
-
-
-class PhoneNumberProperties(TypedDict):
- """Dictionary of properties for a PhoneNumberIdentifier."""
-
- value: str
- """The phone number in E.164 format."""
-
-
-class PhoneNumberIdentifier:
- """Represents a phone number."""
-
- kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER
- """The type of identifier."""
- properties: PhoneNumberProperties
- """The properties of the identifier."""
- raw_id: str
- """The raw ID of the identifier."""
-
- def __init__(self, value: str, **kwargs: Any) -> None:
- """
- :param str value: The phone number.
- :keyword str raw_id: The raw ID of the identifier. If not specified, this will be constructed from
- the 'value' parameter.
- """
- self.properties = PhoneNumberProperties(value=value)
- raw_id: Optional[str] = kwargs.get("raw_id")
- self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties)
-
- def __eq__(self, other):
- try:
- if other.raw_id:
- return self.raw_id == other.raw_id
- return self.raw_id == self._format_raw_id(other.properties)
- except Exception: # pylint:disable=broad-except
- return False
-
- def _format_raw_id(self, properties: PhoneNumberProperties) -> str:
- # We just assume correct E.164 format here because
- # validation should only happen server-side, not client-side.
- value = properties["value"]
- return f"{PHONE_NUMBER_PREFIX}{value}"
-
-
-class UnknownIdentifier:
- """Represents an identifier of an unknown type.
-
- It will be encountered in communications with endpoints that are not
- identifiable by this version of the SDK.
-
- For checking yet unknown identifiers it is better to rely on the presence of the `raw_id` property,
- as new or existing distinct type identifiers always contain the `raw_id` property.
- It is not advisable to rely on the `kind` property with a value `unknown`,
- as it could become a new or existing distinct type in the future.
- """
-
- kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN
- """The type of identifier."""
- properties: Mapping[str, Any]
- """The properties of the identifier."""
- raw_id: str
- """The raw ID of the identifier."""
-
- def __init__(self, identifier: str) -> None:
- """
- :param str identifier: The ID of the identifier.
- """
- self.raw_id = identifier
- self.properties = {}
-
- def __eq__(self, other):
- try:
- return self.raw_id == other.raw_id
- except AttributeError:
- return False
-
-
-class MicrosoftTeamsUserProperties(TypedDict):
- """Dictionary of properties for a MicrosoftTeamsUserIdentifier."""
-
- user_id: str
- """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user."""
- is_anonymous: bool
- """Set this to true if the user is anonymous for example when joining a meeting with a share link."""
- cloud: Union[CommunicationCloudEnvironment, str]
- """Cloud environment that this identifier belongs to."""
-
-
-class MicrosoftTeamsUserIdentifier:
- """Represents an identifier for a Microsoft Teams user."""
-
- kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER
- """The type of identifier."""
- properties: MicrosoftTeamsUserProperties
- """The properties of the identifier."""
- raw_id: str
- """The raw ID of the identifier."""
-
- def __init__(self, user_id: str, **kwargs: Any) -> None:
- """
- :param str user_id: Microsoft Teams user id.
- :keyword bool is_anonymous: `True` if the identifier is anonymous. Default value is `False`.
- :keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`.
- :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
- :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from
- the other properties.
- """
- self.properties = MicrosoftTeamsUserProperties(
- user_id=user_id,
- is_anonymous=kwargs.get("is_anonymous", False),
- cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC,
- )
- raw_id: Optional[str] = kwargs.get("raw_id")
- self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties)
-
- def __eq__(self, other):
- try:
- if other.raw_id:
- return self.raw_id == other.raw_id
- return self.raw_id == self._format_raw_id(other.properties)
- except Exception: # pylint: disable=broad-except
- return False
-
- def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str:
- user_id = properties["user_id"]
- if properties["is_anonymous"]:
- return f"{TEAMS_USER_ANONYMOUS_PREFIX}{user_id}"
- cloud = properties["cloud"]
- if cloud == CommunicationCloudEnvironment.DOD:
- return f"{TEAMS_USER_DOD_CLOUD_PREFIX}{user_id}"
- if cloud == CommunicationCloudEnvironment.GCCH:
- return f"{TEAMS_USER_GCCH_CLOUD_PREFIX}{user_id}"
- if cloud == CommunicationCloudEnvironment.PUBLIC:
- return f"{TEAMS_USER_PUBLIC_CLOUD_PREFIX}{user_id}"
- return f"{TEAMS_USER_PUBLIC_CLOUD_PREFIX}{user_id}"
-
-
-class MicrosoftTeamsAppProperties(TypedDict):
- """Dictionary of properties for a MicrosoftTeamsAppIdentifier."""
-
- app_id: str
- """The id of the Microsoft Teams application."""
- cloud: Union[CommunicationCloudEnvironment, str]
- """Cloud environment that this identifier belongs to."""
-
-
-class _botbackcompatdict(dict):
- """Backwards compatible properties."""
-
- def __getitem__(self, __key: Any) -> Any:
- try:
- return super().__getitem__(__key)
- except KeyError:
- if __key == "bot_id":
- return super().__getitem__("app_id")
- if __key == "is_resource_account_configured":
- return True
- raise
-
-
-class MicrosoftTeamsAppIdentifier:
- """Represents an identifier for a Microsoft Teams application."""
-
- kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP
- """The type of identifier."""
- properties: MicrosoftTeamsAppProperties
- """The properties of the identifier."""
- raw_id: str
- """The raw ID of the identifier."""
-
- def __init__(self, app_id: str, **kwargs: Any) -> None:
- """
- :param str app_id: Microsoft Teams application id.
- :keyword cloud: Cloud environment that the application belongs to. Default value is `PUBLIC`.
- :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
- :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed
- from the other properties.
- """
- self.properties = cast(
- MicrosoftTeamsAppProperties,
- _botbackcompatdict(
- app_id=app_id,
- cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC,
- ),
- )
- raw_id: Optional[str] = kwargs.get("raw_id")
- self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties)
-
- def __eq__(self, other):
- try:
- if other.raw_id:
- return self.raw_id == other.raw_id
- return self.raw_id == self._format_raw_id(other.properties)
- except Exception: # pylint: disable=broad-except
- return False
-
- def _format_raw_id(self, properties: MicrosoftTeamsAppProperties) -> str:
- app_id = properties["app_id"]
- cloud = properties["cloud"]
- if cloud == CommunicationCloudEnvironment.DOD:
- return f"{TEAMS_APP_DOD_CLOUD_PREFIX}{app_id}"
- if cloud == CommunicationCloudEnvironment.GCCH:
- return f"{TEAMS_APP_GCCH_CLOUD_PREFIX}{app_id}"
- return f"{TEAMS_APP_PUBLIC_CLOUD_PREFIX}{app_id}"
-
-
-class _MicrosoftBotIdentifier(MicrosoftTeamsAppIdentifier):
- """Represents an identifier for a Microsoft bot.
-
- DEPRECATED. Only used in cases of backwards compatibility.
- """
-
- def __init__(self, bot_id, **kwargs):
- """
- :param str bot_id: Microsoft bot id.
- :keyword bool is_resource_account_configured: `False` if the identifier is global.
- Default value is `True` for tennantzed bots.
- :keyword cloud: Cloud environment that the bot belongs to. Default value is `PUBLIC`.
- :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment
- """
- warnings.warn(
- "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.",
- DeprecationWarning,
- )
- super().__init__(bot_id, **kwargs)
-
-
-def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: disable=too-many-return-statements
- """
- Creates a CommunicationIdentifier from a given raw ID.
-
- When storing raw IDs use this function to restore the identifier that was encoded in the raw ID.
-
- :param str raw_id: A raw ID to construct the CommunicationIdentifier from.
- :return: The CommunicationIdentifier parsed from the raw_id.
- :rtype: CommunicationIdentifier
- """
- if raw_id.startswith(PHONE_NUMBER_PREFIX):
- return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id)
-
- segments = raw_id.split(":", maxsplit=2)
- if len(segments) < 3:
- return UnknownIdentifier(identifier=raw_id)
-
- prefix = f"{segments[0]}:{segments[1]}:"
- suffix = segments[2]
- if prefix == TEAMS_USER_ANONYMOUS_PREFIX:
- return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id)
- if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX:
- return MicrosoftTeamsUserIdentifier(
- user_id=suffix,
- is_anonymous=False,
- cloud=CommunicationCloudEnvironment.PUBLIC,
- raw_id=raw_id,
- )
- if prefix == TEAMS_USER_DOD_CLOUD_PREFIX:
- return MicrosoftTeamsUserIdentifier(
- user_id=suffix,
- is_anonymous=False,
- cloud=CommunicationCloudEnvironment.DOD,
- raw_id=raw_id,
- )
- if prefix == TEAMS_USER_GCCH_CLOUD_PREFIX:
- return MicrosoftTeamsUserIdentifier(
- user_id=suffix,
- is_anonymous=False,
- cloud=CommunicationCloudEnvironment.GCCH,
- raw_id=raw_id,
- )
- if prefix == TEAMS_APP_PUBLIC_CLOUD_PREFIX:
- return MicrosoftTeamsAppIdentifier(
- app_id=suffix,
- cloud=CommunicationCloudEnvironment.PUBLIC,
- raw_id=raw_id,
- )
- if prefix == TEAMS_APP_DOD_CLOUD_PREFIX:
- return MicrosoftTeamsAppIdentifier(
- app_id=suffix,
- cloud=CommunicationCloudEnvironment.DOD,
- raw_id=raw_id,
- )
- if prefix == TEAMS_APP_GCCH_CLOUD_PREFIX:
- return MicrosoftTeamsAppIdentifier(
- app_id=suffix,
- cloud=CommunicationCloudEnvironment.GCCH,
- raw_id=raw_id,
- )
- if prefix in [
- ACS_USER_PREFIX,
- ACS_USER_DOD_CLOUD_PREFIX,
- ACS_USER_GCCH_CLOUD_PREFIX,
- SPOOL_USER_PREFIX,
- ]:
- return CommunicationUserIdentifier(id=raw_id, raw_id=raw_id)
- return UnknownIdentifier(identifier=raw_id)
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py
deleted file mode 100644
index 79aa48136fd3..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py
+++ /dev/null
@@ -1,121 +0,0 @@
-# ------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# -------------------------------------------------------------------------
-
-import hashlib
-import urllib
-import base64
-import hmac
-from urllib.parse import ParseResult, urlparse
-from typing import Union
-from azure.core.credentials import AzureKeyCredential
-from azure.core.pipeline.policies import SansIOHTTPPolicy
-from .utils import get_current_utc_time
-
-
-class HMACCredentialsPolicy(SansIOHTTPPolicy):
- """Implementation of HMAC authentication policy.
-
- :param str host: The host of the endpoint url for Azure Communication Service resource
- :param access_key: The access key we use to authenticate to the service
- :type access_key: str or AzureKeyCredential
- :param bool decode_url: `True` if there is a need to decode the url. Default value is `False`
- """
-
- def __init__(
- self,
- host, # type: str
- access_key, # type: Union[str, AzureKeyCredential]
- decode_url=False, # type: bool
- ):
- # type: (...) -> None
- super(HMACCredentialsPolicy, self).__init__()
-
- if host.startswith("https://"):
- self._host = host.replace("https://", "")
-
- if host.startswith("http://"):
- self._host = host.replace("http://", "")
-
- self._access_key = access_key
- self._decode_url = decode_url
-
- def _compute_hmac(
- self, value # type: str
- ):
- if isinstance(self._access_key, AzureKeyCredential):
- decoded_secret = base64.b64decode(self._access_key.key)
- else:
- decoded_secret = base64.b64decode(self._access_key)
-
- digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest()
-
- return base64.b64encode(digest).decode("utf-8")
-
- def _sign_request(self, request):
- verb = request.http_request.method.upper()
-
- # Get the path and query from url, which looks like https://host/path/query
- parsed_url: ParseResult = urlparse(request.http_request.url)
- query_url = parsed_url.path
-
- if parsed_url.query:
- query_url += "?" + parsed_url.query
-
- # Need URL() to get a correct encoded key value, from "%3A" to ":", when transport is in type AioHttpTransport.
- # There's a similar scenario in azure-storage-blob and azure-appconfiguration, the check logic is from there.
- try:
- from yarl import URL
- from azure.core.pipeline.transport import ( # pylint:disable=non-abstract-transport-import
- AioHttpTransport,
- )
-
- if (
- isinstance(request.context.transport, AioHttpTransport)
- or isinstance(
- getattr(request.context.transport, "_transport", None),
- AioHttpTransport,
- )
- or isinstance(
- getattr(
- getattr(request.context.transport, "_transport", None),
- "_transport",
- None,
- ),
- AioHttpTransport,
- )
- ):
- query_url = str(URL(query_url))
- except (ImportError, TypeError):
- pass
-
- if self._decode_url:
- query_url = urllib.parse.unquote(query_url)
-
- signed_headers = "x-ms-date;host;x-ms-content-sha256"
-
- utc_now = get_current_utc_time()
- if request.http_request.body is None:
- request.http_request.body = ""
- content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest()
- content_hash = base64.b64encode(content_digest).decode("utf-8")
-
- string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash
-
- signature = self._compute_hmac(string_to_sign)
-
- signature_header = {
- "x-ms-date": utc_now,
- "x-ms-content-sha256": content_hash,
- "x-ms-return-client-request-id": "true",
- "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature,
- }
-
- request.http_request.headers.update(signature_header)
-
- return request
-
- def on_request(self, request):
- self._sign_request(request)
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py
deleted file mode 100644
index 54603e7b32ce..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py
+++ /dev/null
@@ -1,143 +0,0 @@
-# -------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# --------------------------------------------------------------------------
-
-from threading import Lock, Condition, Timer, TIMEOUT_MAX, Event
-from datetime import timedelta
-from typing import Any
-
-from .utils import get_current_utc_as_int
-from .utils import create_access_token
-
-
-class CommunicationTokenCredential(object):
- """Credential type used for authenticating to an Azure Communication service.
- :param str token: The token used to authenticate to an Azure Communication service.
- :keyword token_refresher: The sync token refresher to provide capacity to fetch a fresh token.
- The returned token must be valid (expiration date must be in the future).
- :paramtype token_refresher: Callable[[], AccessToken]
- :keyword bool proactive_refresh: Whether to refresh the token proactively or not.
- If the proactive refreshing is enabled ('proactive_refresh' is true), the credential will use
- a background thread to attempt to refresh the token within 10 minutes before the cached token expires,
- the proactive refresh will request a new token by calling the 'token_refresher' callback.
- When 'proactive_refresh' is enabled, the Credential object must be either run within a context manager
- or the 'close' method must be called once the object usage has been finished.
- :raises: TypeError if paramater 'token' is not a string
- :raises: ValueError if the 'proactive_refresh' is enabled without providing the 'token_refresher' callable.
- """
-
- _ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2
- _DEFAULT_AUTOREFRESH_INTERVAL_MINUTES = 10
-
- def __init__(self, token: str, **kwargs: Any):
- if not isinstance(token, str):
- raise TypeError("Token must be a string.")
- self._token = create_access_token(token)
- self._token_refresher = kwargs.pop("token_refresher", None)
- self._proactive_refresh = kwargs.pop("proactive_refresh", False)
- if self._proactive_refresh and self._token_refresher is None:
- raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.")
- self._timer = None
- self._lock = Condition(Lock())
- self._some_thread_refreshing = False
- self._is_closed = Event()
-
- def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument
- # type (*str, **Any) -> AccessToken
- """The value of the configured token.
- :param any scopes: Scopes to be added to the token.
- :return: AccessToken
- :rtype: ~azure.core.credentials.AccessToken
- """
- if self._proactive_refresh and self._is_closed.is_set():
- raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.")
-
- if not self._token_refresher or not self._is_token_expiring_soon(self._token):
- return self._token
- self._update_token_and_reschedule()
- return self._token
-
- def _update_token_and_reschedule(self):
- should_this_thread_refresh = False
- with self._lock:
- while self._is_token_expiring_soon(self._token):
- if self._some_thread_refreshing:
- if self._is_token_valid(self._token):
- return self._token
- self._wait_till_lock_owner_finishes_refreshing()
- else:
- should_this_thread_refresh = True
- self._some_thread_refreshing = True
- break
-
- if should_this_thread_refresh:
- try:
- new_token = self._token_refresher()
- if not self._is_token_valid(new_token):
- raise ValueError("The token returned from the token_refresher is expired.")
- with self._lock:
- self._token = new_token
- self._some_thread_refreshing = False
- self._lock.notify_all()
- except:
- with self._lock:
- self._some_thread_refreshing = False
- self._lock.notify_all()
- raise
- if self._proactive_refresh:
- self._schedule_refresh()
- return self._token
-
- def _schedule_refresh(self):
- if self._is_closed.is_set():
- return
- if self._timer is not None:
- self._timer.cancel()
-
- token_ttl = self._token.expires_on - get_current_utc_as_int()
-
- if self._is_token_expiring_soon(self._token):
- # Schedule the next refresh for when it reaches a certain percentage of the remaining lifetime.
- timespan = token_ttl // 2
- else:
- # Schedule the next refresh for when it gets in to the soon-to-expire window.
- timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds()
- if timespan <= TIMEOUT_MAX:
- self._timer = Timer(timespan, self._update_token_and_reschedule)
- self._timer.daemon = True
- self._timer.start()
-
- def _wait_till_lock_owner_finishes_refreshing(self):
- self._lock.release()
- self._lock.acquire()
-
- def _is_token_expiring_soon(self, token):
- if self._proactive_refresh:
- interval = timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES)
- else:
- interval = timedelta(minutes=self._ON_DEMAND_REFRESHING_INTERVAL_MINUTES)
- return (token.expires_on - get_current_utc_as_int()) < interval.total_seconds()
-
- @classmethod
- def _is_token_valid(cls, token):
- return get_current_utc_as_int() < token.expires_on
-
- def __enter__(self):
- if self._proactive_refresh:
- if self._is_closed.is_set():
- raise RuntimeError(
- "An instance of CommunicationTokenCredential cannot be reused once it has been closed."
- )
- self._schedule_refresh()
- return self
-
- def __exit__(self, *args):
- self.close()
-
- def close(self) -> None:
- if self._timer is not None:
- self._timer.cancel()
- self._timer = None
- self._is_closed.set()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py
deleted file mode 100644
index 15ad17da1a8c..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py
+++ /dev/null
@@ -1,148 +0,0 @@
-# -------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# --------------------------------------------------------------------------
-
-from asyncio import Condition, Lock, Event
-from datetime import timedelta
-from typing import Any
-import sys
-
-from .utils import get_current_utc_as_int
-from .utils import create_access_token
-from .utils_async import AsyncTimer
-
-
-class CommunicationTokenCredential(object):
- """Credential type used for authenticating to an Azure Communication service.
- :param str token: The token used to authenticate to an Azure Communication service.
- :keyword token_refresher: The async token refresher to provide capacity to fetch a fresh token.
- The returned token must be valid (expiration date must be in the future).
- :paramtype token_refresher: Callable[[], Awaitable[AccessToken]]
- :keyword bool proactive_refresh: Whether to refresh the token proactively or not.
- If the proactive refreshing is enabled ('proactive_refresh' is true), the credential will use
- a background thread to attempt to refresh the token within 10 minutes before the cached token expires,
- the proactive refresh will request a new token by calling the 'token_refresher' callback.
- When 'proactive_refresh is enabled', the Credential object must be either run within a context manager
- or the 'close' method must be called once the object usage has been finished.
- :raises: TypeError if paramater 'token' is not a string
- :raises: ValueError if the 'proactive_refresh' is enabled without providing the 'token_refresher' function.
- """
-
- _ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2
- _DEFAULT_AUTOREFRESH_INTERVAL_MINUTES = 10
-
- def __init__(self, token: str, **kwargs: Any):
- if not isinstance(token, str):
- raise TypeError("Token must be a string.")
- self._token = create_access_token(token)
- self._token_refresher = kwargs.pop("token_refresher", None)
- self._proactive_refresh = kwargs.pop("proactive_refresh", False)
- if self._proactive_refresh and self._token_refresher is None:
- raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.")
- self._timer = None
- self._async_mutex = Lock()
- if sys.version_info[:3] == (3, 10, 0):
- # Workaround for Python 3.10 bug(https://bugs.python.org/issue45416):
- getattr(self._async_mutex, "_get_loop", lambda: None)()
- self._lock = Condition(self._async_mutex)
- self._some_thread_refreshing = False
- self._is_closed = Event()
-
- async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument
- # type (*str, **Any) -> AccessToken
- """The value of the configured token.
- :param any scopes: Scopes to be added to the token.
- :return: AccessToken
- :rtype: ~azure.core.credentials.AccessToken
- """
- if self._proactive_refresh and self._is_closed.is_set():
- raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.")
-
- if not self._token_refresher or not self._is_token_expiring_soon(self._token):
- return self._token
- await self._update_token_and_reschedule()
- return self._token
-
- async def _update_token_and_reschedule(self):
- should_this_thread_refresh = False
- async with self._lock:
- while self._is_token_expiring_soon(self._token):
- if self._some_thread_refreshing:
- if self._is_token_valid(self._token):
- return self._token
- await self._wait_till_lock_owner_finishes_refreshing()
- else:
- should_this_thread_refresh = True
- self._some_thread_refreshing = True
- break
-
- if should_this_thread_refresh:
- try:
- new_token = await self._token_refresher()
- if not self._is_token_valid(new_token):
- raise ValueError("The token returned from the token_refresher is expired.")
- async with self._lock:
- self._token = new_token
- self._some_thread_refreshing = False
- self._lock.notify_all()
- except:
- async with self._lock:
- self._some_thread_refreshing = False
- self._lock.notify_all()
- raise
- if self._proactive_refresh:
- self._schedule_refresh()
- return self._token
-
- def _schedule_refresh(self):
- if self._is_closed.is_set():
- return
- if self._timer is not None:
- self._timer.cancel()
-
- token_ttl = self._token.expires_on - get_current_utc_as_int()
-
- if self._is_token_expiring_soon(self._token):
- # Schedule the next refresh for when it reaches a certain percentage of the remaining lifetime.
- timespan = token_ttl // 2
- else:
- # Schedule the next refresh for when it gets in to the soon-to-expire window.
- timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds()
-
- self._timer = AsyncTimer(timespan, self._update_token_and_reschedule)
- self._timer.start()
-
- async def _wait_till_lock_owner_finishes_refreshing(self):
- self._lock.release()
- await self._lock.acquire()
-
- def _is_token_expiring_soon(self, token):
- if self._proactive_refresh:
- interval = timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES)
- else:
- interval = timedelta(minutes=self._ON_DEMAND_REFRESHING_INTERVAL_MINUTES)
- return (token.expires_on - get_current_utc_as_int()) < interval.total_seconds()
-
- @classmethod
- def _is_token_valid(cls, token):
- return get_current_utc_as_int() < token.expires_on
-
- async def __aenter__(self):
- if self._proactive_refresh:
- if self._is_closed.is_set():
- raise RuntimeError(
- "An instance of CommunicationTokenCredential cannot be reused once it has been closed."
- )
- self._schedule_refresh()
- return self
-
- async def __aexit__(self, *args):
- await self.close()
-
- async def close(self) -> None:
- if self._timer is not None:
- self._timer.cancel()
- self._timer = None
- self._is_closed.set()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py
deleted file mode 100644
index 8576c31ddc56..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py
+++ /dev/null
@@ -1,93 +0,0 @@
-# ------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# -------------------------------------------------------------------------
-
-import base64
-import json
-import calendar
-from typing import cast, Tuple, Optional
-from datetime import datetime
-from azure.core.serialization import TZ_UTC
-from azure.core.credentials import AccessToken
-
-
-def _convert_datetime_to_utc_int(input_datetime) -> int:
- """
- Converts DateTime in local time to the Epoch in UTC in second.
-
- :param input_datetime: Input datetime
- :type input_datetime: datetime
- :return: Integer
- :rtype: int
- """
- return int(calendar.timegm(input_datetime.utctimetuple()))
-
-
-def parse_connection_str(conn_str):
- # type: (Optional[str]) -> Tuple[str, str]
- if conn_str is None:
- raise ValueError("Connection string is undefined.")
- endpoint = None
- shared_access_key = None
- for element in conn_str.split(";"):
- key, _, value = element.partition("=")
- if key.lower() == "endpoint":
- endpoint = value.rstrip("/")
- elif key.lower() == "accesskey":
- shared_access_key = value
- if not all([endpoint, shared_access_key]):
- raise ValueError(
- "Invalid connection string. You can get the connection string from your resource page in the Azure Portal. "
- "The format should be as follows: endpoint=https:///;accesskey="
- )
- left_slash_pos = cast(str, endpoint).find("//")
- if left_slash_pos != -1:
- host = cast(str, endpoint)[left_slash_pos + 2 :]
- else:
- host = str(endpoint)
-
- return host, str(shared_access_key)
-
-
-def get_current_utc_time():
- # type: () -> str
- return str(datetime.now(tz=TZ_UTC).strftime("%a, %d %b %Y %H:%M:%S ")) + "GMT"
-
-
-def get_current_utc_as_int():
- # type: () -> int
- current_utc_datetime = datetime.utcnow()
- return _convert_datetime_to_utc_int(current_utc_datetime)
-
-
-def create_access_token(token):
- # type: (str) -> AccessToken
- """Creates an instance of azure.core.credentials.AccessToken from a
- string token. The input string is jwt token in the following form:
- ..
- This method looks into the token_payload which is a json and extracts the expiry time
- for that token and creates a tuple of type azure.core.credentials.AccessToken
- (, )
- :param token: User token
- :type token: str
- :return: Instance of azure.core.credentials.AccessToken - token and expiry date of it
- :rtype: ~azure.core.credentials.AccessToken
- """
-
- token_parse_err_msg = "Token is not formatted correctly"
- parts = token.split(".")
-
- if len(parts) < 3:
- raise ValueError(token_parse_err_msg)
-
- try:
- padded_base64_payload = base64.b64decode(parts[1] + "==").decode("ascii")
- payload = json.loads(padded_base64_payload)
- return AccessToken(
- token,
- _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)),
- )
- except ValueError as val_error:
- raise ValueError(token_parse_err_msg) from val_error
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py
deleted file mode 100644
index 86e0e04d273c..000000000000
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py
+++ /dev/null
@@ -1,31 +0,0 @@
-# ------------------------------------------------------------------------
-# Copyright (c) Microsoft Corporation. All rights reserved.
-# Licensed under the MIT License. See License.txt in the project root for
-# license information.
-# -------------------------------------------------------------------------
-
-import asyncio
-
-
-class AsyncTimer:
- """A non-blocking timer, that calls a function after a specified number of seconds:
- :param int interval: time interval in seconds
- :param callable callback: function to be called after the interval has elapsed
- """
-
- def __init__(self, interval, callback):
- self._interval = interval
- self._callback = callback
- self._task = None
-
- def start(self):
- self._task = asyncio.ensure_future(self._job())
-
- async def _job(self):
- await asyncio.sleep(self._interval)
- await self._callback()
-
- def cancel(self):
- if self._task is not None:
- self._task.cancel()
- self._task = None
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py
index 2671426c897b..a7d4ec5935fa 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py
@@ -13,7 +13,6 @@
from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from azure.core import PipelineClient
from ._serialization import Deserializer, Serializer
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py
index f6cd39818b76..a1f432eddc4e 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py
@@ -6,4 +6,4 @@
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
-VERSION = "1.1.0b2"
+VERSION = "1.1.0b1"
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py
index 2cad3c9bd6b0..a00bc5c726de 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py
@@ -5,13 +5,19 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import JobRouterAdministrationClient
-from ._patch import JobRouterClient
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+from ._client import JobRouterAdministrationClient # type: ignore
+from ._client import JobRouterClient # type: ignore
try:
from ._patch import __all__ as _patch_all
- from ._patch import * # pylint: disable=unused-wildcard-import
+ from ._patch import *
except ImportError:
_patch_all = []
from ._patch import patch_sdk as _patch_sdk
@@ -20,6 +26,6 @@
"JobRouterAdministrationClient",
"JobRouterClient",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py
index ddf6e6531806..7b712c4040ac 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py
@@ -8,6 +8,7 @@
from copy import deepcopy
from typing import Any, Awaitable
+from typing_extensions import Self
from azure.core import AsyncPipelineClient
from azure.core.pipeline import policies
@@ -18,9 +19,7 @@
from ._operations import JobRouterAdministrationClientOperationsMixin, JobRouterClientOperationsMixin
-class JobRouterAdministrationClient(
- JobRouterAdministrationClientOperationsMixin
-): # pylint: disable=client-accepts-api-version-keyword
+class JobRouterAdministrationClient(JobRouterAdministrationClientOperationsMixin):
"""JobRouterAdministrationClient.
:param endpoint: Uri of your Communication resource. Required.
@@ -81,7 +80,7 @@ def send_request(
request_copy = deepcopy(request)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
@@ -90,7 +89,7 @@ def send_request(
async def close(self) -> None:
await self._client.close()
- async def __aenter__(self) -> "JobRouterAdministrationClient":
+ async def __aenter__(self) -> Self:
await self._client.__aenter__()
return self
@@ -98,7 +97,7 @@ async def __aexit__(self, *exc_details: Any) -> None:
await self._client.__aexit__(*exc_details)
-class JobRouterClient(JobRouterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword
+class JobRouterClient(JobRouterClientOperationsMixin):
"""JobRouterClient.
:param endpoint: Uri of your Communication resource. Required.
@@ -159,7 +158,7 @@ def send_request(
request_copy = deepcopy(request)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments)
@@ -168,7 +167,7 @@ def send_request(
async def close(self) -> None:
await self._client.close()
- async def __aenter__(self) -> "JobRouterClient":
+ async def __aenter__(self) -> Self:
await self._client.__aenter__()
return self
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py
index 038bdbcfaf66..b44082aaa65a 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py
@@ -51,7 +51,7 @@ def _configure(self, **kwargs: Any) -> None:
self.authentication_policy = kwargs.get("authentication_policy")
-class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long
+class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes
"""Configuration for JobRouterClient.
Note that all parameters used to create this instance are saved as instance
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py
index 06eb1614ceb7..462bfe7de7f9 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py
@@ -5,17 +5,23 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._patch import JobRouterAdministrationClientOperationsMixin
-from ._patch import JobRouterClientOperationsMixin
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+from ._operations import JobRouterAdministrationClientOperationsMixin # type: ignore
+from ._operations import JobRouterClientOperationsMixin # type: ignore
from ._patch import __all__ as _patch_all
-from ._patch import * # pylint: disable=unused-wildcard-import
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
"JobRouterAdministrationClientOperationsMixin",
"JobRouterClientOperationsMixin",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py
index f56155fa52fb..44d440d83c20 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py
@@ -1,4 +1,4 @@
-# pylint: disable=too-many-lines,too-many-statements
+# pylint: disable=too-many-lines
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
@@ -10,7 +10,7 @@
from io import IOBase
import json
import sys
-from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
+from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, overload
import urllib.parse
from azure.core import MatchConditions
@@ -22,6 +22,8 @@
ResourceModifiedError,
ResourceNotFoundError,
ResourceNotModifiedError,
+ StreamClosedError,
+ StreamConsumedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
@@ -72,7 +74,7 @@
if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
else:
- from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
+ from typing import MutableMapping # type: ignore
JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
@@ -81,6 +83,7 @@
class JobRouterAdministrationClientOperationsMixin( # pylint: disable=name-too-long
JobRouterAdministrationClientMixinABC
):
+
@overload
async def upsert_distribution_policy(
self,
@@ -93,7 +96,6 @@ async def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -116,243 +118,6 @@ async def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@overload
@@ -367,7 +132,6 @@ async def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -390,162 +154,6 @@ async def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@overload
@@ -560,7 +168,6 @@ async def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -583,162 +190,6 @@ async def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
@distributed_trace_async
@@ -752,7 +203,6 @@ async def upsert_distribution_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a distribution policy.
Creates or updates a distribution policy.
@@ -773,245 +223,8 @@ async def upsert_distribution_policy(
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1050,7 +263,7 @@ async def upsert_distribution_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1063,28 +276,21 @@ async def upsert_distribution_policy(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.DistributionPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.DistributionPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.DistributionPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -1093,7 +299,6 @@ async def upsert_distribution_policy(
@distributed_trace_async
async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> _models.DistributionPolicy:
- # pylint: disable=line-too-long
"""Retrieves an existing distribution policy by Id.
Retrieves an existing distribution policy by Id.
@@ -1103,93 +308,8 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A
:return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DistributionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1209,7 +329,7 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1222,7 +342,10 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -1240,10 +363,8 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.DistributionPolicy"]:
- # pylint: disable=line-too-long
+ def list_distribution_policies(self, **kwargs: Any) -> AsyncIterable["_models.DistributionPolicy"]:
"""Retrieves existing distribution policies.
Retrieves existing distribution policies.
@@ -1252,91 +373,6 @@ def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.D
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.DistributionPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "bestWorker":
- distribution_mode = {
- "kind": "bestWorker",
- "bypassSelectors": bool, # Optional. If set to true, then router will match
- workers to jobs even if they don't match label selectors. Warning: You may get
- workers that are not qualified for a job they are matched with if you set this
- variable to true. This flag is intended more for temporary usage. By default, set
- to false.
- "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active
- concurrent offers a job can have.
- "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of
- active concurrent offers a job can have.
- "scoringRule": router_rule,
- "scoringRuleOptions": {
- "batchSize": 0, # Optional. Set batch size when
- 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.
- "descendingOrder": bool, # Optional. If false, will sort scores by
- ascending order. By default, set to true.
- "isBatchScoringEnabled": bool, # Optional. If set to true, will
- score workers in batches, and the parameter name of the worker labels will be
- sent as ``workers``. By default, set to false and the parameter name for the
- worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize'
- to set batch size.
- "scoringParameters": [
- "str" # Optional. List of extra parameters from a job that
- will be sent as part of the payload to scoring rule. If not set, a job's
- labels (sent in the payload as ``job``"" ) and a job's worker selectors
- (sent in the payload as ``selectors``"" ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring
- payload.
- ]
- }
- }
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a distribution policy. Required.
- "mode": distribution_mode,
- "name": "str", # Optional. Friendly name of this policy.
- "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which
- any offers created under this policy will be expired.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -1344,7 +380,7 @@ def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.D
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.DistributionPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1362,9 +398,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1382,9 +416,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1407,8 +439,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -1417,9 +447,7 @@ async def get_next(next_link=None):
return AsyncItemPaged(get_next, extract_data)
@distributed_trace_async
- async def delete_distribution_policy( # pylint: disable=inconsistent-return-statements
- self, distribution_policy_id: str, **kwargs: Any
- ) -> None:
+ async def delete_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> None:
"""Delete a distribution policy by Id.
Delete a distribution policy by Id.
@@ -1430,7 +458,7 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -1450,7 +478,7 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -1462,8 +490,6 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -1482,7 +508,6 @@ async def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -1505,192 +530,6 @@ async def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@overload
@@ -1705,7 +544,6 @@ async def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -1728,126 +566,6 @@ async def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@overload
@@ -1862,7 +580,6 @@ async def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -1885,126 +602,6 @@ async def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
@distributed_trace_async
@@ -2018,7 +615,6 @@ async def upsert_classification_policy(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Creates or updates a classification policy.
Creates or updates a classification policy.
@@ -2039,194 +635,8 @@ async def upsert_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2265,7 +675,7 @@ async def upsert_classification_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2278,28 +688,21 @@ async def upsert_classification_policy(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ClassificationPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ClassificationPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.ClassificationPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -2310,7 +713,6 @@ async def upsert_classification_policy(
async def get_classification_policy(
self, classification_policy_id: str, **kwargs: Any
) -> _models.ClassificationPolicy:
- # pylint: disable=line-too-long
"""Retrieves an existing classification policy by Id.
Retrieves an existing classification policy by Id.
@@ -2320,78 +722,8 @@ async def get_classification_policy(
:return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2411,7 +743,7 @@ async def get_classification_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2424,7 +756,10 @@ async def get_classification_policy(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2442,10 +777,8 @@ async def get_classification_policy(
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.ClassificationPolicy"]:
- # pylint: disable=line-too-long
+ def list_classification_policies(self, **kwargs: Any) -> AsyncIterable["_models.ClassificationPolicy"]:
"""Retrieves existing classification policies.
Retrieves existing classification policies.
@@ -2454,76 +787,6 @@ def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "directMap":
- router_rule = {
- "kind": "directMap"
- }
-
- # JSON input template for discriminator value "expression":
- router_rule = {
- "expression": "str", # An expression to evaluate. Should contain return
- statement with calculated values. Required.
- "kind": "expression",
- "language": "str" # Optional. The expression language to compile to and
- execute. "powerFx"
- }
-
- # JSON input template for discriminator value "function":
- router_rule = {
- "functionUri": "str", # URL for Azure Function. Required.
- "kind": "function",
- "credential": {
- "appKey": "str", # Optional. Access key scoped to a Azure Function
- app. This key grants access to all functions under the app.
- "clientId": "str", # Optional. Client id, when AppKey is provided In
- context of Azure function, this is usually the name of the key.
- "functionKey": "str" # Optional. Access key scoped to a particular
- function.
- }
- }
-
- # JSON input template for discriminator value "static":
- router_rule = {
- "kind": "static",
- "value": {} # Optional. The static value this rule always returns. Values
- must be primitive values - number, string, boolean.
- }
-
- # JSON input template for discriminator value "webhook":
- router_rule = {
- "kind": "webhook",
- "authorizationServerUri": "str", # Optional. Uri for Authorization Server.
- "clientCredential": {
- "clientId": "str", # Optional. ClientId for Contoso Authorization
- server.
- "clientSecret": "str" # Optional. Client secret for Contoso
- Authorization server.
- },
- "webhookUri": "str" # Optional. Uri for Contoso's Web Server.
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a classification policy. Required.
- "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if
- queue selector attachments doesn't find a match.
- "name": "str", # Optional. Friendly name of this policy.
- "prioritizationRule": router_rule,
- "queueSelectorAttachments": [
- queue_selector_attachment
- ],
- "workerSelectorAttachments": [
- worker_selector_attachment
- ]
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -2531,7 +794,7 @@ def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.ClassificationPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2549,9 +812,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2569,9 +830,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2594,8 +853,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2604,9 +861,7 @@ async def get_next(next_link=None):
return AsyncItemPaged(get_next, extract_data)
@distributed_trace_async
- async def delete_classification_policy( # pylint: disable=inconsistent-return-statements
- self, classification_policy_id: str, **kwargs: Any
- ) -> None:
+ async def delete_classification_policy(self, classification_policy_id: str, **kwargs: Any) -> None:
"""Delete a classification policy by Id.
Delete a classification policy by Id.
@@ -2617,7 +872,7 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2637,7 +892,7 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2649,8 +904,6 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -2691,41 +944,6 @@ async def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@overload
@@ -2762,25 +980,6 @@ async def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@overload
@@ -2817,25 +1016,6 @@ async def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
@distributed_trace_async
@@ -2869,43 +1049,8 @@ async def upsert_exception_policy(
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -2944,7 +1089,7 @@ async def upsert_exception_policy(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -2957,28 +1102,21 @@ async def upsert_exception_policy(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ExceptionPolicy, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.ExceptionPolicy, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.ExceptionPolicy, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -2996,27 +1134,8 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) ->
:return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3036,7 +1155,7 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) ->
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3049,7 +1168,10 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) ->
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3067,9 +1189,8 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) ->
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.ExceptionPolicy"]:
+ def list_exception_policies(self, **kwargs: Any) -> AsyncIterable["_models.ExceptionPolicy"]:
"""Retrieves existing exception policies.
Retrieves existing exception policies.
@@ -3078,25 +1199,6 @@ def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.Exce
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of an exception policy. Required.
- "exceptionRules": [
- {
- "actions": [
- exception_action
- ],
- "id": "str", # Id of an exception rule. Required.
- "trigger": exception_trigger
- }
- ],
- "name": "str" # Optional. Friendly name of this policy.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -3104,7 +1206,7 @@ def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.Exce
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.ExceptionPolicy]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3122,9 +1224,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3142,9 +1242,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3167,8 +1265,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3177,9 +1273,7 @@ async def get_next(next_link=None):
return AsyncItemPaged(get_next, extract_data)
@distributed_trace_async
- async def delete_exception_policy( # pylint: disable=inconsistent-return-statements
- self, exception_policy_id: str, **kwargs: Any
- ) -> None:
+ async def delete_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> None:
"""Deletes a exception policy by Id.
Deletes a exception policy by Id.
@@ -3190,7 +1284,7 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3210,7 +1304,7 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3222,8 +1316,6 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3242,7 +1334,6 @@ async def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -3263,43 +1354,8 @@ async def upsert_queue(
:keyword match_condition: The match condition to use upon the etag. Default value is None.
:paramtype match_condition: ~azure.core.MatchConditions
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
+ :rtype: ~azure.communication.jobrouter.models.RouterQueue
+ :raises ~azure.core.exceptions.HttpResponseError:
"""
@overload
@@ -3314,7 +1370,6 @@ async def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -3337,25 +1392,6 @@ async def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
@overload
@@ -3370,7 +1406,6 @@ async def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -3393,25 +1428,6 @@ async def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
@distributed_trace_async
@@ -3425,7 +1441,6 @@ async def upsert_queue(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Creates or updates a queue.
Creates or updates a queue.
@@ -3446,43 +1461,8 @@ async def upsert_queue(
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3521,7 +1501,7 @@ async def upsert_queue(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3534,28 +1514,21 @@ async def upsert_queue(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterQueue, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterQueue, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterQueue, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -3564,7 +1537,6 @@ async def upsert_queue(
@distributed_trace_async
async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
- # pylint: disable=line-too-long
"""Retrieves an existing queue by Id.
Retrieves an existing queue by Id.
@@ -3574,27 +1546,8 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
:return: RouterQueue. The RouterQueue is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueue
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3614,7 +1567,7 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3627,7 +1580,10 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3645,10 +1601,8 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue:
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
- def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]:
- # pylint: disable=line-too-long
+ def list_queues(self, **kwargs: Any) -> AsyncIterable["_models.RouterQueue"]:
"""Retrieves existing queues.
Retrieves existing queues.
@@ -3657,25 +1611,6 @@ def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]:
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterQueue]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a queue. Required.
- "distributionPolicyId": "str", # Optional. Id of a distribution policy that
- will determine how a job is distributed to workers.
- "exceptionPolicyId": "str", # Optional. Id of an exception policy that
- determines various job escalation rules.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "name": "str" # Optional. Friendly name of this queue.
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -3683,7 +1618,7 @@ def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]:
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterQueue]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3701,9 +1636,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3721,9 +1654,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3746,8 +1677,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3756,9 +1685,7 @@ async def get_next(next_link=None):
return AsyncItemPaged(get_next, extract_data)
@distributed_trace_async
- async def delete_queue( # pylint: disable=inconsistent-return-statements
- self, queue_id: str, **kwargs: Any
- ) -> None:
+ async def delete_queue(self, queue_id: str, **kwargs: Any) -> None:
"""Deletes a queue by Id.
Deletes a queue by Id.
@@ -3769,7 +1696,7 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -3789,7 +1716,7 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -3801,8 +1728,6 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -3811,6 +1736,7 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements
class JobRouterClientOperationsMixin(JobRouterClientMixinABC):
+
@overload
async def upsert_job(
self,
@@ -3823,7 +1749,6 @@ async def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -3846,256 +1771,6 @@ async def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -4110,7 +1785,6 @@ async def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -4133,142 +1807,6 @@ async def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -4283,7 +1821,6 @@ async def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -4306,142 +1843,6 @@ async def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
@distributed_trace_async
@@ -4455,7 +1856,6 @@ async def upsert_job(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Creates or updates a router job.
Creates or updates a router job.
@@ -4476,258 +1876,8 @@ async def upsert_job(
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The input is polymorphic. The following are possible polymorphic inputs based off
- discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4766,7 +1916,7 @@ async def upsert_job(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4779,28 +1929,21 @@ async def upsert_job(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterJob, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterJob, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterJob, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -4809,7 +1952,6 @@ async def upsert_job(
@distributed_trace_async
async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
- # pylint: disable=line-too-long
"""Retrieves an existing job by Id.
Retrieves an existing job by Id.
@@ -4819,126 +1961,8 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
:return: RouterJob. The RouterJob is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJob
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -4958,7 +1982,7 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -4971,7 +1995,10 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -4990,7 +2017,7 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob:
return deserialized # type: ignore
@distributed_trace_async
- async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements
+ async def delete_job(self, job_id: str, **kwargs: Any) -> None:
"""Deletes a job and all of its traces.
Deletes a job and all of its traces.
@@ -5001,7 +2028,7 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5021,7 +2048,7 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5033,8 +2060,6 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -5042,35 +2067,30 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab
return cls(pipeline_response, None, {}) # type: ignore
@overload
- async def _reclassify_job( # pylint: disable=protected-access
+ async def _reclassify_job(
self,
job_id: str,
options: Optional[_models._models.ReclassifyJobOptions] = None,
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
-
+ ) -> _models.ReclassifyJobResult: ...
@overload
- async def _reclassify_job( # pylint: disable=protected-access
+ async def _reclassify_job(
self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
-
+ ) -> _models.ReclassifyJobResult: ...
@overload
- async def _reclassify_job( # pylint: disable=protected-access
+ async def _reclassify_job(
self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
- ...
+ ) -> _models.ReclassifyJobResult: ...
@distributed_trace_async
- async def _reclassify_job( # pylint: disable=protected-access
+ async def _reclassify_job(
self,
job_id: str,
options: Optional[Union[_models._models.ReclassifyJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.ReclassifyJobResult:
+ ) -> _models.ReclassifyJobResult:
"""Reclassify a job.
Reclassify a job.
@@ -5079,18 +2099,13 @@ async def _reclassify_job( # pylint: disable=protected-access
:type job_id: str
:param options: Request object for reclassifying a job. Is one of the following types:
ReclassifyJobOptions, JSON, IO[bytes] Default value is None.
- :type options: ~azure.communication.jobrouter.models.ReclassifyJobOptions or JSON or IO[bytes]
+ :type options: ~azure.communication.jobrouter.models._models.ReclassifyJobOptions or JSON or
+ IO[bytes]
:return: ReclassifyJobResult. The ReclassifyJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.ReclassifyJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {}
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5102,7 +2117,7 @@ async def _reclassify_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.ReclassifyJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.ReclassifyJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -5123,7 +2138,7 @@ async def _reclassify_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5136,16 +2151,17 @@ async def _reclassify_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.ReclassifyJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.ReclassifyJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -5153,33 +2169,27 @@ async def _reclassify_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- async def _cancel_job( # pylint: disable=protected-access
+ async def _cancel_job(
self,
job_id: str,
options: Optional[_models.CancelJobOptions] = None,
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
-
+ ) -> _models.CancelJobResult: ...
@overload
- async def _cancel_job( # pylint: disable=protected-access
+ async def _cancel_job(
self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
-
+ ) -> _models.CancelJobResult: ...
@overload
- async def _cancel_job( # pylint: disable=protected-access
+ async def _cancel_job(
self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any
- ) -> _models._models.CancelJobResult:
- ...
+ ) -> _models.CancelJobResult: ...
@distributed_trace_async
- async def _cancel_job( # pylint: disable=protected-access
+ async def _cancel_job(
self, job_id: str, options: Optional[Union[_models.CancelJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any
- ) -> _models._models.CancelJobResult:
- # pylint: disable=line-too-long
+ ) -> _models.CancelJobResult:
"""Submits request to cancel an existing job by Id while supplying free-form cancellation reason.
Submits request to cancel an existing job by Id while supplying free-form cancellation reason.
@@ -5192,20 +2202,8 @@ async def _cancel_job( # pylint: disable=protected-access
:return: CancelJobResult. The CancelJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CancelJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "dispositionCode": "str", # Optional. Indicates the outcome of a job,
- populate this field with your own custom values. If not provided, default value
- of "Cancelled" is set.
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5217,7 +2215,7 @@ async def _cancel_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CancelJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CancelJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -5238,7 +2236,7 @@ async def _cancel_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5251,16 +2249,17 @@ async def _cancel_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CancelJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CancelJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -5268,7 +2267,7 @@ async def _cancel_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- async def _complete_job( # pylint: disable=protected-access
+ async def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -5276,11 +2275,9 @@ async def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
-
+ ) -> _models.CompleteJobResult: ...
@overload
- async def _complete_job( # pylint: disable=protected-access
+ async def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -5288,11 +2285,9 @@ async def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
-
+ ) -> _models.CompleteJobResult: ...
@overload
- async def _complete_job( # pylint: disable=protected-access
+ async def _complete_job(
self,
job_id: str,
assignment_id: str,
@@ -5300,17 +2295,16 @@ async def _complete_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
- ...
+ ) -> _models.CompleteJobResult: ...
@distributed_trace_async
- async def _complete_job( # pylint: disable=protected-access
+ async def _complete_job(
self,
job_id: str,
assignment_id: str,
options: Optional[Union[_models.CompleteJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.CompleteJobResult:
+ ) -> _models.CompleteJobResult:
"""Completes an assigned job.
Completes an assigned job.
@@ -5325,17 +2319,8 @@ async def _complete_job( # pylint: disable=protected-access
:return: CompleteJobResult. The CompleteJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CompleteJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5347,7 +2332,7 @@ async def _complete_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CompleteJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CompleteJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -5369,7 +2354,7 @@ async def _complete_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5382,16 +2367,17 @@ async def _complete_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CompleteJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CompleteJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -5399,7 +2385,7 @@ async def _complete_job( # pylint: disable=protected-access
return deserialized # type: ignore
@overload
- async def _close_job( # pylint: disable=protected-access
+ async def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -5407,11 +2393,9 @@ async def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
-
+ ) -> _models.CloseJobResult: ...
@overload
- async def _close_job( # pylint: disable=protected-access
+ async def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -5419,11 +2403,9 @@ async def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
-
+ ) -> _models.CloseJobResult: ...
@overload
- async def _close_job( # pylint: disable=protected-access
+ async def _close_job(
self,
job_id: str,
assignment_id: str,
@@ -5431,18 +2413,16 @@ async def _close_job( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- ...
+ ) -> _models.CloseJobResult: ...
@distributed_trace_async
- async def _close_job( # pylint: disable=protected-access
+ async def _close_job(
self,
job_id: str,
assignment_id: str,
options: Optional[Union[_models.CloseJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.CloseJobResult:
- # pylint: disable=line-too-long
+ ) -> _models.CloseJobResult:
"""Closes a completed job.
Closes a completed job.
@@ -5457,23 +2437,8 @@ async def _close_job( # pylint: disable=protected-access
:return: CloseJobResult. The CloseJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.CloseJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "closeAt": "2020-02-20 00:00:00", # Optional. If not provided, worker
- capacity is released immediately along with a JobClosedEvent notification. If
- provided, worker capacity is released along with a JobClosedEvent notification at
- a future time in UTC.
- "dispositionCode": "str", # Optional. Indicates the outcome of a job,
- populate this field with your own custom values.
- "note": "str" # Optional. A note that will be appended to a job's Notes
- collection with the current timestamp.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5485,7 +2450,7 @@ async def _close_job( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.CloseJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access
+ cls: ClsType[_models.CloseJobResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -5507,7 +2472,7 @@ async def _close_job( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5520,23 +2485,23 @@ async def _close_job( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.CloseJobResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.CloseJobResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
return deserialized # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
def list_jobs(
self,
@@ -5548,8 +2513,7 @@ def list_jobs(
scheduled_before: Optional[datetime.datetime] = None,
scheduled_after: Optional[datetime.datetime] = None,
**kwargs: Any
- ) -> AsyncItemPaged["_models.RouterJob"]:
- # pylint: disable=line-too-long
+ ) -> AsyncIterable["_models.RouterJob"]:
"""Retrieves list of jobs based on filter parameters.
Retrieves list of jobs based on filter parameters.
@@ -5576,124 +2540,6 @@ def list_jobs(
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterJob]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # The response is polymorphic. The following are possible polymorphic responses based
- off discriminator "kind":
-
- # JSON input template for discriminator value "queueAndMatch":
- job_matching_mode = {
- "kind": "queueAndMatch"
- }
-
- # JSON input template for discriminator value "scheduleAndSuspend":
- job_matching_mode = {
- "kind": "scheduleAndSuspend",
- "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required.
- }
-
- # JSON input template for discriminator value "suspend":
- job_matching_mode = {
- "kind": "suspend"
- }
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a job. Required.
- "assignments": {
- "str": {
- "assignedAt": "2020-02-20 00:00:00", # Timestamp when the
- job was assigned to a worker in UTC. Required.
- "assignmentId": "str", # Id of a job assignment. Required.
- "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as closed after being completed in UTC.
- "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the job was marked as completed after being assigned in UTC.
- "workerId": "str" # Optional. Id of the Worker assigned to
- the job.
- }
- },
- "attachedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "channelId": "str", # Optional. The channel identifier. eg. voice, chat,
- etc.
- "channelReference": "str", # Optional. Reference to an external parent
- context, eg. call ID.
- "classificationPolicyId": "str", # Optional. Id of a classification policy
- used for classifying this job.
- "dispositionCode": "str", # Optional. Reason code for cancelled or closed
- jobs.
- "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued
- in UTC.
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "matchingMode": job_matching_mode,
- "notes": [
- {
- "message": "str", # The message contained in the note.
- Required.
- "addedAt": "2020-02-20 00:00:00" # Optional. The time at
- which the note was added in UTC. If not provided, will default to the
- current time.
- }
- ],
- "priority": 0, # Optional. Priority of this job.
- "queueId": "str", # Optional. Id of a queue that this job is queued to.
- "requestedWorkerSelectors": [
- {
- "key": "str", # The label key to query against. Required.
- "labelOperator": "str", # Describes how the value of the
- label is compared to the value defined on the worker selector. Required.
- Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual",
- "greaterThan", and "greaterThanOrEqual".
- "expedite": bool, # Optional. Pushes a job to the front of
- the queue as long as this selector is active.
- "expiresAfterSeconds": 0.0, # Optional. Describes how long
- this label selector is valid in seconds.
- "expiresAt": "2020-02-20 00:00:00", # Optional. The time at
- which this worker selector expires in UTC.
- "status": "str", # Optional. Status of the worker selector.
- Known values are: "active" and "expired".
- "value": {} # Optional. The value to compare against the
- actual label value with the given operator. Values must be primitive
- values - number, string, boolean.
- }
- ],
- "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be
- scheduled to be enqueued at a given time.
- "status": "str", # Optional. The status of the job. Known values are:
- "pendingClassification", "queued", "assigned", "completed", "closed",
- "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled",
- "scheduleFailed", and "waitingForActivation".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this job. Values must be primitive values - number, string, boolean.
- }
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -5701,7 +2547,7 @@ def list_jobs(
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterJob]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5725,9 +2571,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5745,9 +2589,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5770,8 +2612,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -5791,23 +2631,8 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router
MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterJobPositionDetails
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "estimatedWaitTimeMinutes": 0.0, # Estimated wait time of the job rounded up
- to the nearest minute. Required.
- "jobId": "str", # Id of the job these details are about. Required.
- "position": 0, # Position of the job in question within that queue.
- Required.
- "queueId": "str", # Id of the queue this job is enqueued in. Required.
- "queueLength": 0 # Length of the queue: total number of enqueued jobs.
- Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -5827,7 +2652,7 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -5840,7 +2665,10 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -5864,7 +2692,6 @@ async def unassign_job(
content_type: str = "application/json",
**kwargs: Any
) -> _models.UnassignJobResult:
- # pylint: disable=line-too-long
"""Unassign a job.
Unassign a job.
@@ -5881,22 +2708,6 @@ async def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "suspendMatching": bool # Optional. If SuspendMatching is true, then a job
- is not queued for re-matching with a worker.
- }
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@overload
@@ -5925,16 +2736,6 @@ async def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@overload
@@ -5963,16 +2764,6 @@ async def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
@distributed_trace_async
@@ -5983,7 +2774,6 @@ async def unassign_job(
options: Optional[Union[_models.UnassignJobOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
) -> _models.UnassignJobResult:
- # pylint: disable=line-too-long
"""Unassign a job.
Unassign a job.
@@ -5998,24 +2788,8 @@ async def unassign_job(
:return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.UnassignJobResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "suspendMatching": bool # Optional. If SuspendMatching is true, then a job
- is not queued for re-matching with a worker.
- }
-
- # response body for status code(s): 200
- response == {
- "jobId": "str", # Id of an unassigned job. Required.
- "unassignmentCount": 0 # The number of times a job is unassigned. At a
- maximum 3. Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6049,7 +2823,7 @@ async def unassign_job(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6062,7 +2836,10 @@ async def unassign_job(
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6091,20 +2868,8 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -
:return: AcceptJobOfferResult. The AcceptJobOfferResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.AcceptJobOfferResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "assignmentId": "str", # Id of job assignment that assigns a worker that has
- accepted an offer to a job. Required.
- "jobId": "str", # Id of the job assigned. Required.
- "workerId": "str" # Id of the worker that has been assigned this job.
- Required.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6125,7 +2890,7 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6138,7 +2903,10 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6153,7 +2921,7 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -
return deserialized # type: ignore
@overload
- async def _decline_job_offer( # pylint: disable=protected-access
+ async def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -6161,11 +2929,9 @@ async def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
-
+ ) -> _models.DeclineJobOfferResult: ...
@overload
- async def _decline_job_offer( # pylint: disable=protected-access
+ async def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -6173,11 +2939,9 @@ async def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
-
+ ) -> _models.DeclineJobOfferResult: ...
@overload
- async def _decline_job_offer( # pylint: disable=protected-access
+ async def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
@@ -6185,18 +2949,16 @@ async def _decline_job_offer( # pylint: disable=protected-access
*,
content_type: str = "application/json",
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- ...
+ ) -> _models.DeclineJobOfferResult: ...
@distributed_trace_async
- async def _decline_job_offer( # pylint: disable=protected-access
+ async def _decline_job_offer(
self,
worker_id: str,
offer_id: str,
options: Optional[Union[_models.DeclineJobOfferOptions, JSON, IO[bytes]]] = None,
**kwargs: Any
- ) -> _models._models.DeclineJobOfferResult:
- # pylint: disable=line-too-long
+ ) -> _models.DeclineJobOfferResult:
"""Declines an offer to work on a job.
Declines an offer to work on a job.
@@ -6212,21 +2974,8 @@ async def _decline_job_offer( # pylint: disable=protected-access
:return: DeclineJobOfferResult. The DeclineJobOfferResult is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.DeclineJobOfferResult
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- options = {
- "retryOfferAt": "2020-02-20 00:00:00" # Optional. If the RetryOfferAt is not
- provided, then this job will not be offered again to the worker who declined this
- job unless the worker is de-registered and re-registered. If a RetryOfferAt time
- is provided, then the job will be re-matched to eligible workers at the retry
- time in UTC. The worker that declined the job will also be eligible for the job
- at that time.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6238,9 +2987,7 @@ async def _decline_job_offer( # pylint: disable=protected-access
_params = kwargs.pop("params", {}) or {}
content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None))
- cls: ClsType[_models._models.DeclineJobOfferResult] = kwargs.pop( # pylint: disable=protected-access
- "cls", None
- )
+ cls: ClsType[_models.DeclineJobOfferResult] = kwargs.pop("cls", None)
content_type = content_type or "application/json"
_content = None
@@ -6262,7 +3009,7 @@ async def _decline_job_offer( # pylint: disable=protected-access
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6275,16 +3022,17 @@ async def _decline_job_offer( # pylint: disable=protected-access
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if _stream:
deserialized = response.iter_bytes()
else:
- deserialized = _deserialize(
- _models._models.DeclineJobOfferResult, response.json() # pylint: disable=protected-access
- )
+ deserialized = _deserialize(_models.DeclineJobOfferResult, response.json())
if cls:
return cls(pipeline_response, deserialized, {}) # type: ignore
@@ -6293,7 +3041,6 @@ async def _decline_job_offer( # pylint: disable=protected-access
@distributed_trace_async
async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQueueStatistics:
- # pylint: disable=line-too-long
"""Retrieves a queue's statistics.
Retrieves a queue's statistics.
@@ -6303,23 +3050,8 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro
:return: RouterQueueStatistics. The RouterQueueStatistics is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterQueueStatistics
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "length": 0, # Length of the queue: total number of enqueued jobs. Required.
- "queueId": "str", # Id of the queue these details are about. Required.
- "estimatedWaitTimeMinutes": {
- "str": 0.0 # Optional. The estimated wait time of this queue rounded
- up to the nearest minute, grouped by job priority.
- },
- "longestJobWaitTimeMinutes": 0.0 # Optional. The wait time of the job that
- has been enqueued in this queue for the longest.
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6339,7 +3071,7 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6352,7 +3084,10 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -6378,7 +3113,6 @@ async def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -6401,133 +3135,6 @@ async def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -6542,7 +3149,6 @@ async def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -6565,71 +3171,6 @@ async def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@overload
@@ -6644,7 +3185,6 @@ async def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -6667,71 +3207,6 @@ async def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
@distributed_trace_async
@@ -6745,7 +3220,6 @@ async def upsert_worker(
match_condition: Optional[MatchConditions] = None,
**kwargs: Any
) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Creates or updates a worker.
Creates or updates a worker.
@@ -6766,135 +3240,8 @@ async def upsert_worker(
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # JSON input template you can fill out and use as your body input.
- resource = {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
-
- # response body for status code(s): 201, 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -6933,7 +3280,7 @@ async def upsert_worker(
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -6946,28 +3293,21 @@ async def upsert_worker(
if response.status_code not in [200, 201]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
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["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
-
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterWorker, response.json())
-
- if response.status_code == 201:
- response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
- response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
+ response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag"))
+ response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified"))
- if _stream:
- deserialized = response.iter_bytes()
- else:
- deserialized = _deserialize(_models.RouterWorker, response.json())
+ if _stream:
+ deserialized = response.iter_bytes()
+ else:
+ deserialized = _deserialize(_models.RouterWorker, response.json())
if cls:
return cls(pipeline_response, deserialized, response_headers) # type: ignore
@@ -6976,7 +3316,6 @@ async def upsert_worker(
@distributed_trace_async
async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker:
- # pylint: disable=line-too-long
"""Retrieves an existing worker by Id.
Retrieves an existing worker by Id.
@@ -6986,73 +3325,8 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke
:return: RouterWorker. The RouterWorker is compatible with MutableMapping
:rtype: ~azure.communication.jobrouter.models.RouterWorker
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7072,7 +3346,7 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7085,7 +3359,10 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke
if response.status_code not in [200]:
if _stream:
- await response.read() # Load the body in memory and close the socket
+ try:
+ await response.read() # Load the body in memory and close the socket
+ except (StreamConsumedError, StreamClosedError):
+ pass
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
@@ -7104,9 +3381,7 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke
return deserialized # type: ignore
@distributed_trace_async
- async def delete_worker( # pylint: disable=inconsistent-return-statements
- self, worker_id: str, **kwargs: Any
- ) -> None:
+ async def delete_worker(self, worker_id: str, **kwargs: Any) -> None:
"""Deletes a worker and all of its traces.
Deletes a worker and all of its traces.
@@ -7117,7 +3392,7 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements
:rtype: None
:raises ~azure.core.exceptions.HttpResponseError:
"""
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7137,7 +3412,7 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7149,15 +3424,12 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements
response = pipeline_response.http_response
if response.status_code not in [204]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
if cls:
return cls(pipeline_response, None, {}) # type: ignore
- # https://github.com/Azure/autorest.python/issues/2262
@distributed_trace
def list_workers(
self,
@@ -7167,8 +3439,7 @@ def list_workers(
queue_id: Optional[str] = None,
has_capacity: Optional[bool] = None,
**kwargs: Any
- ) -> AsyncItemPaged["_models.RouterWorker"]:
- # pylint: disable=line-too-long
+ ) -> AsyncIterable["_models.RouterWorker"]:
"""Retrieves existing workers.
Retrieves existing workers.
@@ -7191,71 +3462,6 @@ def list_workers(
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterWorker]
:raises ~azure.core.exceptions.HttpResponseError:
-
- Example:
- .. code-block:: python
-
- # response body for status code(s): 200
- response == {
- "etag": "str", # The entity tag for this resource. Required.
- "id": "str", # Id of a worker. Required.
- "assignedJobs": [
- {
- "assignedAt": "2020-02-20 00:00:00", # The assignment time
- of the job in UTC. Required.
- "assignmentId": "str", # Id of the assignment. Required.
- "capacityCost": 0, # The amount of capacity this assignment
- has consumed on the worker. Required.
- "jobId": "str" # Id of the job assigned. Required.
- }
- ],
- "availableForOffers": bool, # Optional. A flag indicating this worker is
- open to receive offers or not.
- "capacity": 0, # Optional. The total capacity score this worker has to
- manage multiple concurrent jobs.
- "channels": [
- {
- "capacityCostPerJob": 0, # The amount of capacity that an
- instance of a job of this channel will consume of the total worker
- capacity. Required.
- "channelId": "str", # Id of a channel. Required.
- "maxNumberOfJobs": 0 # Optional. The maximum number of jobs
- that can be supported concurrently for this channel.
- }
- ],
- "labels": {
- "str": {} # Optional. A set of key/value pairs that are identifying
- attributes used by the rules engines to make decisions. Values must be
- primitive values - number, string, boolean.
- },
- "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A
- value of '1' means all capacity is consumed. A value of '0' means no capacity is
- currently consumed.
- "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only
- receive up to this many new offers at a time.
- "offers": [
- {
- "capacityCost": 0, # The capacity cost consumed by the job
- offer. Required.
- "jobId": "str", # Id of the job. Required.
- "offerId": "str", # Id of an offer. Required.
- "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp
- when the offer will expire in UTC.
- "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp
- when the offer was created in UTC.
- }
- ],
- "queues": [
- "str" # Optional. Collection of queue(s) that this worker can
- receive work from.
- ],
- "state": "str", # Optional. Current state of a worker. Known values are:
- "active", "draining", and "inactive".
- "tags": {
- "str": {} # Optional. A set of non-identifying attributes attached
- to this worker. Values must be primitive values - number, string, boolean.
- }
- }
"""
_headers = kwargs.pop("headers", {}) or {}
_params = kwargs.pop("params", {}) or {}
@@ -7263,7 +3469,7 @@ def list_workers(
maxpagesize = kwargs.pop("maxpagesize", None)
cls: ClsType[List[_models.RouterWorker]] = kwargs.pop("cls", None)
- error_map = {
+ error_map: MutableMapping = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
@@ -7285,9 +3491,7 @@ def prepare_request(next_link=None):
params=_params,
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7305,9 +3509,7 @@ def prepare_request(next_link=None):
"GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
)
path_format_arguments = {
- "endpoint": self._serialize.url(
- "self._config.endpoint", self._config.endpoint, "str", skip_quote=True
- ),
+ "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"),
}
_request.url = self._client.format_url(_request.url, **path_format_arguments)
@@ -7330,8 +3532,6 @@ async def get_next(next_link=None):
response = pipeline_response.http_response
if response.status_code not in [200]:
- if _stream:
- await response.read() # Load the body in memory and close the socket
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response)
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py
index dc7e9c9541ff..f7dd32510333 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py
@@ -6,2117 +6,9 @@
Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-import sys
-import datetime
-from typing import List, Any, Optional, Dict, Union, overload, IO, Literal
+from typing import List
-from azure.core import MatchConditions
-from azure.core.tracing.decorator import distributed_trace
-from azure.core.async_paging import AsyncItemPaged
-from azure.core.tracing.decorator_async import distributed_trace_async
-
-from ... import models as _models
-from ._operations import (
- JobRouterClientOperationsMixin as JobRouterClientOperationsMixinGenerated,
- JobRouterAdministrationClientOperationsMixin as JobRouterAdministrationClientOperationsMixinGenerated,
-)
-from ..._model_base import _deserialize_datetime as _convert_str_to_datetime
-
-if sys.version_info >= (3, 9):
- from collections.abc import MutableMapping
-else:
- from typing import MutableMapping # type: ignore
-
-
-JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
-
-
-class JobRouterAdministrationClientOperationsMixin(
- JobRouterAdministrationClientOperationsMixinGenerated
-): # pylint:disable=too-many-lines,line-too-long,name-too-long,arguments-differ
- # region ExceptionPolicy
- @overload
- async def upsert_exception_policy( # pylint: disable=arguments-differ
- self,
- exception_policy_id: str,
- *,
- exception_rules: Optional[List[_models.ExceptionRule]],
- name: Optional[str],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Update an exception policy.
-
- :param str exception_policy_id: Id of the exception policy.
- :keyword exception_rules: (Optional) A collection of exception rules on the exception policy.
- :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]]
- :keyword Optional[str] name: The name of this policy.
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :return: Instance of ExceptionPolicy
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops_async.py
- :start-after: [START update_exception_policy_async]
- :end-before: [END update_exception_policy_async]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to update an exception policy
- """
-
- @overload
- async def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: _models.ExceptionPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.ExceptionPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_exception_policy(
- self,
- exception_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Creates or updates a exception policy.
-
- Creates or updates a exception policy.
-
- :param exception_policy_id: The Id of the exception policy. Required.
- :type exception_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_exception_policy( # pylint: disable=docstring-missing-param
- self, exception_policy_id: str, *args: Union[_models.ExceptionPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.ExceptionPolicy:
- """Update an exception policy.
-
- :param str exception_policy_id: Id of the exception policy.
-
- :keyword exception_rules: (Optional) A collection of exception rules on the exception
- policy.
- :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ExceptionPolicy
- :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops_async.py
- :start-after: [START update_exception_policy_async]
- :end-before: [END update_exception_policy_async]
- :language: python
- :dedent: 8
- :caption: Using a JobRouterAdministrationClient to update an exception policy
- """
- if not exception_policy_id:
- raise ValueError("exception_policy_id cannot be None.")
-
- exception_policy: Union[_models.ExceptionPolicy, JSON, IO[bytes]] = _models.ExceptionPolicy()
- if len(args) == 1:
- exception_policy = args[0]
-
- patch = exception_policy
- if isinstance(exception_policy, _models.ExceptionPolicy):
- patch = _models.ExceptionPolicy(
- name=kwargs.pop("name", exception_policy.name),
- exception_rules=kwargs.pop("exception_rules", exception_policy.exception_rules),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_exception_policy(
- exception_policy_id=exception_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_exception_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> AsyncItemPaged[_models.ExceptionPolicy]:
- """Retrieves existing exception policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of ExceptionPolicyItem
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ExceptionPolicyItem]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops_async.py
- :start-after: [START list_exception_policies_async]
- :end-before: [END list_exception_policies_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list exception policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/exception_policy_crud_ops_async.py
- :start-after: [START list_exception_policies_batched_async]
- :end-before: [END list_exception_policies_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list exception policies in batches
- """
- return super().list_exception_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion ExceptionPolicy
-
- # region DistributionPolicy
- @overload
- async def upsert_distribution_policy( # pylint: disable=arguments-differ
- self,
- distribution_policy_id: str,
- *,
- name: Optional[str],
- offer_expires_after_seconds: Optional[float],
- mode: Optional[Union[_models.BestWorkerMode, _models.LongestIdleMode, _models.RoundRobinMode]],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Update a distribution policy.
-
- :param str distribution_policy_id: Id of the distribution policy.
-
- :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy
- will be governed by the offer time to live.
-
- :keyword mode: Specified distribution mode
- :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode,
- ~azure.communication.jobrouter.models.LongestIdleMode,
- ~azure.communication.jobrouter.models.RoundRobinMode]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of DistributionPolicy
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py
- :start-after: [START update_distribution_policy_async]
- :end-before: [END update_distribution_policy_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a distribution policy
- """
-
- @overload
- async def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: _models.DistributionPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.DistributionPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_distribution_policy(
- self,
- distribution_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Creates or updates a distribution policy.
-
- Creates or updates a distribution policy.
-
- :param distribution_policy_id: The unique identifier of the policy. Required.
- :type distribution_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_distribution_policy( # pylint: disable=docstring-missing-param
- self, distribution_policy_id: str, *args: Union[_models.DistributionPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.DistributionPolicy:
- """Update a distribution policy.
-
- :param str distribution_policy_id: Id of the distribution policy.
-
- :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy
- will be governed by the offer time to live.
-
- :keyword mode: Specified distribution mode
- :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode,
- ~azure.communication.jobrouter.models.LongestIdleMode,
- ~azure.communication.jobrouter.models.RoundRobinMode]]
-
- :keyword Optional[str] name: The name of this policy.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of DistributionPolicy
- :rtype: ~azure.communication.jobrouter.models.DistributionPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py
- :start-after: [START update_distribution_policy_async]
- :end-before: [END update_distribution_policy_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a distribution policy
- """
- if not distribution_policy_id:
- raise ValueError("distribution_policy_id cannot be None.")
-
- distribution_policy: Union[_models.DistributionPolicy, JSON, IO[bytes]] = _models.DistributionPolicy()
- if len(args) == 1:
- distribution_policy = args[0]
-
- patch = distribution_policy
- if isinstance(distribution_policy, _models.DistributionPolicy):
- patch = _models.DistributionPolicy(
- name=kwargs.pop("name", distribution_policy.name),
- offer_expires_after_seconds=kwargs.pop(
- "offer_expires_after_seconds", distribution_policy.offer_expires_after_seconds
- ),
- mode=kwargs.pop("mode", distribution_policy.mode),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_distribution_policy(
- distribution_policy_id=distribution_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_distribution_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> AsyncItemPaged[_models.DistributionPolicy]:
- """Retrieves existing distribution policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of DistributionPolicy
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.DistributionPolicy]
- :raises: ~azure.core.exceptions.HttpResponseError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py
- :start-after: [START list_distribution_policies_async]
- :end-before: [END list_distribution_policies_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list distribution policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py
- :start-after: [START list_distribution_policies_batched_async]
- :end-before: [END list_distribution_policies_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list distribution policies in batches
- """
- return super().list_distribution_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion DistributionPolicy
-
- # region Queue
- @overload
- async def upsert_queue( # pylint: disable=arguments-differ
- self,
- queue_id: str,
- *,
- distribution_policy_id: Optional[str],
- name: Optional[str],
- labels: Optional[Dict[str, Union[int, float, str, bool]]],
- exception_policy_id: Optional[str],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Update a job queue
-
- :param str queue_id: Id of the queue.
-
- :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine
- how a job is distributed to workers.
-
- :keyword Optional[str] name: The name of this queue.
-
- :keyword labels: A set of key/value pairs that are
- identifying attributes used by the rules engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]]
-
- :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various
- job escalation rules.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterQueue
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops_async.py
- :start-after: [START update_queue_async]
- :end-before: [END update_queue_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a queue
- """
-
- @overload
- async def upsert_queue(
- self,
- queue_id: str,
- resource: _models.RouterQueue,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterQueue
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_queue(
- self,
- queue_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_queue(
- self,
- queue_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterQueue:
- """Creates or updates a queue.
-
- Creates or updates a queue.
-
- :param queue_id: The Id of this queue. Required.
- :type queue_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterQueue. The RouterQueue is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_queue( # pylint: disable=docstring-missing-param
- self, queue_id: str, *args: Union[_models.RouterQueue, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.RouterQueue:
- """Update a job queue
-
- :param str queue_id: Id of the queue.
-
- :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine
- how a job is distributed to workers.
-
- :keyword Optional[str] name: The name of this queue.
-
- :keyword labels: A set of key/value pairs that are
- identifying attributes used by the rules engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]]
-
- :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various
- job escalation rules.
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterQueue
- :rtype: ~azure.communication.jobrouter.models.RouterQueue
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops_async.py
- :start-after: [START update_queue_async]
- :end-before: [END update_queue_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a queue
- """
- if not queue_id:
- raise ValueError("queue_id cannot be None.")
-
- queue: Union[_models.RouterQueue, JSON, IO[bytes]] = _models.RouterQueue()
- if len(args) == 1:
- queue = args[0]
-
- patch = queue
- if isinstance(queue, _models.RouterQueue):
- patch = _models.RouterQueue(
- name=kwargs.pop("name", queue.name),
- distribution_policy_id=kwargs.pop("distribution_policy_id", queue.distribution_policy_id),
- labels=kwargs.pop("labels", queue.labels),
- exception_policy_id=kwargs.pop("exception_policy_id", queue.exception_policy_id),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_queue(
- queue_id=queue_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_queues(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> AsyncItemPaged[_models.RouterQueue]:
- """Retrieves existing queues.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterQueue
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterQueue]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops_async.py
- :start-after: [START list_queues_async]
- :end-before: [END list_queues_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list queues
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/job_queue_crud_ops_async.py
- :start-after: [START list_queues_batched_async]
- :end-before: [END list_queues_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list queues in batches
- """
-
- return super().list_queues(maxpagesize=results_per_page, **kwargs)
-
- # endregion Queue
-
- # region ClassificationPolicy
- @overload
- async def upsert_classification_policy( # pylint: disable=arguments-differ
- self,
- classification_policy_id: str,
- *,
- name: Optional[str],
- fallback_queue_id: Optional[str],
- queue_selectors: Optional[
- List[
- Union[
- _models.StaticQueueSelectorAttachment,
- _models.ConditionalQueueSelectorAttachment,
- _models.RuleEngineQueueSelectorAttachment,
- _models.PassThroughQueueSelectorAttachment,
- _models.WeightedAllocationQueueSelectorAttachment,
- ]
- ]
- ], # pylint: disable=line-too-long
- prioritization_rule: Optional[
- Union[
- _models.StaticRouterRule,
- _models.ExpressionRouterRule,
- _models.FunctionRouterRule,
- _models.WebhookRouterRule,
- ]
- ], # pylint: disable=line-too-long
- worker_selectors: Optional[
- List[
- Union[
- _models.StaticWorkerSelectorAttachment,
- _models.ConditionalWorkerSelectorAttachment,
- _models.RuleEngineWorkerSelectorAttachment,
- _models.PassThroughWorkerSelectorAttachment,
- _models.WeightedAllocationWorkerSelectorAttachment,
- ]
- ]
- ], # pylint: disable=line-too-long
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Update a classification policy
-
- :param str classification_policy_id: Id of the classification policy.
-
- :keyword Optional[str] name: Friendly name of this policy.
-
- :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match.
- :paramtype fallback_queue_id: Optional[str]
-
- :keyword queue_selectors: The queue selectors to resolve a queue for a given job.
- :paramtype queue_selectors: Optional[List[Union[
- ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]]
-
- :keyword prioritization_rule: The rule to determine a priority score for a given job.
- :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule,
- ~azure.communication.jobrouter.models.ExpressionRouterRule,
- ~azure.communication.jobrouter.models.FunctionRouterRule,
- ~azure.communication.jobrouter.models.WebhookRouterRule]]
-
- :keyword worker_selectors: The worker label selectors to attach to a given job.
- :paramtype worker_selectors: Optional[List[Union[~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ClassificationPolicy
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops_async.py
- :start-after: [START update_classification_policy_async]
- :end-before: [END update_classification_policy_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a classification policy
- """
-
- @overload
- async def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: _models.ClassificationPolicy,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.ClassificationPolicy
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_classification_policy(
- self,
- classification_policy_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Creates or updates a classification policy.
-
- Creates or updates a classification policy.
-
- :param classification_policy_id: Unique identifier of this policy. Required.
- :type classification_policy_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_classification_policy( # pylint: disable=docstring-missing-param
- self, classification_policy_id: str, *args: Union[_models.ClassificationPolicy, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.ClassificationPolicy:
- """Update a classification policy
-
- :param str classification_policy_id: Id of the classification policy.
-
- :keyword Optional[str] name: Friendly name of this policy.
-
- :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match.
- :paramtype fallback_queue_id: Optional[str]
-
- :keyword queue_selectors: The queue selectors to resolve a queue for a given job.
- :paramtype queue_selectors: Optional[List[Union[
- ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]]
-
- :keyword prioritization_rule: The rule to determine a priority score for a given job.
- :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule,
- ~azure.communication.jobrouter.models.ExpressionRouterRule,
- ~azure.communication.jobrouter.models.FunctionRouterRule,
- ~azure.communication.jobrouter.models.WebhookRouterRule]]
-
- :keyword worker_selectors: The worker label selectors to attach to a given job.
- :paramtype worker_selectors: Optional[List[Union[~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment,
- ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of ClassificationPolicy
- :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops_async.py
- :start-after: [START update_classification_policy_async]
- :end-before: [END update_classification_policy_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to update a classification policy
- """
- if not classification_policy_id:
- raise ValueError("classification_policy_id cannot be None.")
-
- classification_policy: Union[_models.ClassificationPolicy, JSON, IO[bytes]] = _models.ClassificationPolicy()
- if len(args) == 1:
- classification_policy = args[0]
-
- patch = classification_policy
- if isinstance(classification_policy, _models.ClassificationPolicy):
- patch = _models.ClassificationPolicy(
- name=kwargs.pop("name", classification_policy.name),
- fallback_queue_id=kwargs.pop("fallback_queue_id", classification_policy.fallback_queue_id),
- queue_selector_attachments=kwargs.pop(
- "queue_selector_attachments", classification_policy.queue_selector_attachments
- ),
- prioritization_rule=kwargs.pop("prioritization_rule", classification_policy.prioritization_rule),
- worker_selector_attachments=kwargs.pop(
- "worker_selector_attachments", classification_policy.worker_selector_attachments
- ),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_classification_policy(
- classification_policy_id=classification_policy_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_classification_policies(
- self, *, results_per_page: Optional[int] = None, **kwargs: Any
- ) -> AsyncItemPaged[_models.ClassificationPolicy]:
- """Retrieves existing classification policies.
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of ClassificationPolicy
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops_async.py
- :start-after: [START list_classification_policies_async]
- :end-before: [END list_classification_policies_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list classification policies
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/classification_policy_crud_ops_async.py
- :start-after: [START list_classification_policies_batched_async]
- :end-before: [END list_classification_policies_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterAdministrationClient to list classification policies in batches
- """
-
- return super().list_classification_policies(maxpagesize=results_per_page, **kwargs)
-
- # endregion ClassificationPolicy
-
-
-class JobRouterClientOperationsMixin(JobRouterClientOperationsMixinGenerated):
- # region Worker
- @overload
- async def upsert_worker( # pylint: disable=arguments-differ
- self,
- worker_id: str,
- *,
- queues: Optional[List[str]],
- capacity: Optional[int],
- labels: Optional[Dict[str, Union[int, float, str, bool]]],
- tags: Optional[Dict[str, Union[int, float, str, bool]]],
- channels: Optional[List[_models.RouterChannel]],
- available_for_offers: Optional[bool],
- max_concurrent_offers: Optional[int],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Update a router worker.
-
- :param str worker_id: Id of the worker.
-
- :keyword queues: The queue(s) that this worker can receive work from.
- :paramtype queues: Optional[List[str]]
-
- :keyword capacity: The total capacity score this worker has to manage multiple concurrent
- jobs.
- :paramtype capacity: Optional[int]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword channels: The channel(s) this worker can handle and their impact on the
- workers capacity.
- :paramtype channels: Optional[List[~azure.communication.jobrouter.models.RouterChannel]]
-
- :keyword available_for_offers: A flag indicating this worker is open to receive offers or not.
- :paramtype available_for_offers: Optional[bool]
-
- :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new
- offers at a time.
- :paramtype max_concurrent_offers: Optional[int]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterWorker
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START update_worker_async]
- :end-before: [END update_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops.py
- :start-after: [START register_worker_async]
- :end-before: [END register_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START deregister_worker_async]
- :end-before: [END deregister_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to de-register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START create_worker_w_limit_concurrent_offers_async]
- :end-before: [END create_worker_w_limit_concurrent_offers_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to create a worker with concurrent offer limit
-
- """
-
- @overload
- async def upsert_worker(
- self,
- worker_id: str,
- resource: _models.RouterWorker,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterWorker
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_worker(
- self,
- worker_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_worker(
- self,
- worker_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterWorker:
- """Creates or updates a worker.
-
- Creates or updates a worker.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterWorker. The RouterWorker is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_worker( # pylint: disable=docstring-missing-param
- self, worker_id: str, *args: Union[_models.RouterWorker, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.RouterWorker:
- """Update a router worker.
-
- :param str worker_id: Id of the worker.
-
- :keyword queues: The queue(s) that this worker can receive work from.
- :paramtype queues: Optional[List[str]]
-
- :keyword capacity: The total capacity score this worker has to manage multiple concurrent
- jobs.
- :paramtype capacity: Optional[int]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword channels: The channel(s) this worker can handle and their impact on the
- workers capacity.
- :paramtype channels: Optional[List[~azure.communication.jobrouter.models.RouterChannel]]
-
- :keyword available_for_offers: A flag indicating this worker is open to receive offers or not.
- :paramtype available_for_offers: Optional[bool]
-
- :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new
- offers at a time.
- :paramtype max_concurrent_offers: Optional[int]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterWorker
- :rtype: ~azure.communication.jobrouter.models.RouterWorker
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START update_worker_async]
- :end-before: [END update_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START register_worker_async]
- :end-before: [END register_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to register a worker
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START deregister_worker_async]
- :end-before: [END deregister_worker_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to de-register a worker
- """
- if not worker_id:
- raise ValueError("worker_id cannot be None.")
-
- router_worker: Union[_models.RouterWorker, JSON, IO[bytes]] = _models.RouterWorker()
- if len(args) == 1:
- router_worker = args[0]
-
- patch = router_worker
- if isinstance(router_worker, _models.RouterWorker):
- patch = _models.RouterWorker(
- queues=kwargs.pop("queues", router_worker.queues),
- capacity=kwargs.pop("capacity", router_worker.capacity),
- labels=kwargs.pop("labels", router_worker.labels),
- tags=kwargs.pop("tags", router_worker.tags),
- channels=kwargs.pop("channels", router_worker.channels),
- available_for_offers=kwargs.pop("available_for_offers", router_worker.available_for_offers),
- max_concurrent_offers=kwargs.pop("max_concurrent_offers", router_worker.max_concurrent_offers),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_worker(
- worker_id=worker_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_workers(
- self,
- *,
- state: Optional[Union[str, _models.RouterWorkerState, Literal["all"]]] = "all",
- channel_id: Optional[str] = None,
- queue_id: Optional[str] = None,
- has_capacity: Optional[bool] = None,
- results_per_page: Optional[int] = None,
- **kwargs: Any
- ) -> AsyncItemPaged[_models.RouterWorker]:
- """Retrieves existing workers.
-
- :keyword state: If specified, select workers by worker status. Default value is "all".
- Accepted value(s): active, draining, inactive, all
- :paramtype state: Optional[Union[str, ~azure.communication.jobrouter.models.RouterWorkerState, Literal["all"]]]
-
- :keyword channel_id: If specified, select workers who have a channel configuration
- with this channel. Default value is None.
- :paramtype channel_id: Optional[str]
-
- :keyword queue_id: If specified, select workers who are assigned to this queue.
- Default value is None.
- :paramtype queue_id: Optional[str]
-
- :keyword has_capacity: If set to true, select only workers who have capacity for the
- channel specified by ``channelId`` or for any channel
- :paramtype has_capacity: Optional[bool]
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterWorker
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterWorker]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START list_workers_async]
- :end-before: [END list_workers_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve workers
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_worker_crud_ops_async.py
- :start-after: [START list_workers_batched_async]
- :end-before: [END list_workers_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve workers in batches
- """
- return super().list_workers(
- maxpagesize=results_per_page,
- state=state,
- channel_id=channel_id,
- queue_id=queue_id,
- has_capacity=has_capacity,
- **kwargs
- )
-
- # endregion Worker
-
- # region Job
- @overload
- async def upsert_job( # pylint: disable=arguments-differ
- self,
- job_id: str,
- *,
- channel_reference: Optional[str],
- channel_id: Optional[str],
- classification_policy_id: Optional[str],
- queue_id: Optional[str],
- priority: Optional[int],
- disposition_code: Optional[str],
- requested_worker_selectors: Optional[List[_models.RouterWorkerSelector]],
- labels: Optional[Dict[str, Union[int, float, str, bool, None]]],
- tags: Optional[Dict[str, Union[int, float, str, bool, None]]],
- notes: Optional[Dict[datetime.datetime, str]],
- matching_mode: Optional[_models.JobMatchingMode],
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Update a job.
-
- :param str job_id: Id of the job.
-
- :keyword channel_reference: Reference to an external parent context, eg. call ID.
- :paramtype channel_reference: Optional[str]
-
- :keyword channel_id: The channel identifier. eg. voice, chat, etc.
- :paramtype channel_id: Optional[str]
-
- :keyword classification_policy_id: The Id of the Classification policy used for classifying a
- job.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword queue_id: The Id of the Queue that this job is queued to.
- :paramtype queue_id: Optional[str]
-
- :keyword priority: The priority of this job.
- :paramtype priority: Optional[int]
-
- :keyword disposition_code: Reason code for cancelled or closed jobs.
- :paramtype disposition_code: Optional[str]
-
- :keyword requested_worker_selectors: A collection of manually specified label selectors, which
- a worker must satisfy in order to process this job.
- :paramtype requested_worker_selectors: Optional[List[
- ~azure.communication.jobrouter.models.RouterWorkerSelector]]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this job.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword notes: Notes attached to a job, sorted by timestamp.
- :paramtype notes: Optional[Dict[~datetime.datetime, str]]
-
- :keyword matching_mode: If set, determines how a job will be matched
- :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterJob
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START update_job_async]
- :end-before: [END update_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a job
- """
-
- @overload
- async def upsert_job(
- self,
- job_id: str,
- resource: _models.RouterJob,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: ~azure.communication.jobrouter.models.RouterJob
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_job(
- self,
- job_id: str,
- resource: JSON,
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: JSON
- :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- @overload
- async def upsert_job(
- self,
- job_id: str,
- resource: IO[bytes],
- *,
- content_type: str = "application/merge-patch+json",
- if_unmodified_since: Optional[datetime.datetime] = None,
- etag: Optional[str] = None,
- match_condition: Optional[MatchConditions] = None,
- **kwargs: Any
- ) -> _models.RouterJob:
- """Creates or updates a router job.
-
- Creates or updates a router job.
-
- :param job_id: The id of the job. Required.
- :type job_id: str
- :param resource: The resource instance. Required.
- :type resource: IO[bytes]
- :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
- Default value is "application/merge-patch+json".
- :paramtype content_type: str
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
- :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You
- will have to context manage the returned stream.
- :return: RouterJob. The RouterJob is compatible with MutableMapping
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises ~azure.core.exceptions.HttpResponseError:
- """
-
- async def upsert_job( # pylint: disable=docstring-missing-param
- self, job_id: str, *args: Union[_models.RouterJob, JSON, IO[bytes]], **kwargs: Any
- ) -> _models.RouterJob:
- """Update a job.
-
- :param str job_id: Id of the job.
-
- :keyword channel_reference: Reference to an external parent context, eg. call ID.
- :paramtype channel_reference: Optional[str]
-
- :keyword channel_id: The channel identifier. eg. voice, chat, etc.
- :paramtype channel_id: Optional[str]
-
- :keyword classification_policy_id: The Id of the Classification policy used for classifying a
- job.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword queue_id: The Id of the Queue that this job is queued to.
- :paramtype queue_id: Optional[str]
-
- :keyword priority: The priority of this job.
- :paramtype priority: Optional[int]
-
- :keyword disposition_code: Reason code for cancelled or closed jobs.
- :paramtype disposition_code: Optional[str]
-
- :keyword requested_worker_selectors: A collection of manually specified label selectors, which
- a worker must satisfy in order to process this job.
- :paramtype requested_worker_selectors: Optional[List[
- ~azure.communication.jobrouter.models.RouterWorkerSelector]]
-
- :keyword labels: A set of key/value pairs that are identifying attributes used by the rules
- engines to make decisions.
- :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword tags: A set of tags. A set of non-identifying attributes attached to this job.
- :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]]
-
- :keyword notes: Notes attached to a job, sorted by timestamp.
- :paramtype notes: Optional[Dict[~datetime.datetime, str]]
-
- :keyword matching_mode: If set, determines how a job will be matched
- :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode]
-
- :keyword if_unmodified_since: The request should only proceed if the entity was not modified
- after this time. Default value is None.
- :paramtype if_unmodified_since: ~datetime.datetime
- :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is
- None.
- :paramtype etag: str
- :keyword match_condition: The match condition to use upon the etag. Default value is None.
- :paramtype match_condition: ~azure.core.MatchConditions
-
- :return: Instance of RouterJob
- :rtype: ~azure.communication.jobrouter.models.RouterJob
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START update_job_async]
- :end-before: [END update_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to update a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- router_job: Union[_models.RouterJob, JSON, IO[bytes]] = _models.RouterJob()
- if len(args) == 1:
- router_job = args[0]
-
- patch = router_job
- if isinstance(router_job, _models.RouterJob):
- patch = _models.RouterJob(
- channel_reference=kwargs.pop("channel_reference", router_job.channel_reference),
- channel_id=kwargs.pop("channel_id", router_job.channel_id),
- classification_policy_id=kwargs.pop("classification_policy_id", router_job.classification_policy_id),
- queue_id=kwargs.pop("queue_id", router_job.queue_id),
- priority=kwargs.pop("priority", router_job.priority),
- disposition_code=kwargs.pop("disposition_code", router_job.disposition_code),
- requested_worker_selectors=kwargs.pop(
- "requested_worker_selectors", router_job.requested_worker_selectors
- ),
- labels=kwargs.pop("labels", router_job.labels),
- tags=kwargs.pop("tags", router_job.tags),
- notes=kwargs.pop("notes", router_job.notes),
- matching_mode=kwargs.pop("matching_mode", router_job.matching_mode),
- )
-
- if_unmodified_since = kwargs.pop("if_unmodified_since", None)
- etag = kwargs.pop("etag", None)
- match_condition = kwargs.pop("match_condition", None)
-
- return await super().upsert_job(
- job_id=job_id,
- resource=patch,
- if_unmodified_since=if_unmodified_since,
- etag=etag,
- match_condition=match_condition,
- **kwargs
- )
-
- @distributed_trace
- def list_jobs(
- self,
- *,
- status: Optional[Union[str, _models.RouterJobStatus, Literal["all", "active"]]] = "all",
- channel_id: Optional[str] = None,
- queue_id: Optional[str] = None,
- classification_policy_id: Optional[str] = None,
- scheduled_before: Optional[Union[str, datetime.datetime]] = None,
- scheduled_after: Optional[Union[str, datetime.datetime]] = None,
- results_per_page: Optional[int] = None,
- **kwargs: Any
- ) -> AsyncItemPaged[_models.RouterJob]:
- """Retrieves list of jobs based on filter parameters.
-
- :keyword status: If specified, filter jobs by status. Default value is "all".
- Accepted value(s): pendingClassification, queued, assigned, completed, closed, cancelled,
- classificationFailed, active, all
- :paramtype status: Optional[Union[
- str, ~azure.communication.jobrouter.models.RouterJobStatus, Literal["all","active"]]]
-
- :keyword channel_id: If specified, filter jobs by channel. Default value is None.
- :paramtype channel_id: Optional[str]
-
- :keyword queue_id: If specified, filter jobs by queue. Default value is None.
- :paramtype queue_id: Optional[str]
-
- :keyword classification_policy_id: If specified, filter jobs by classificationPolicy. Default value is None.
- :paramtype classification_policy_id: Optional[str]
-
- :keyword scheduled_before: If specified, filter on jobs that was scheduled before or
- at given timestamp. Range: (-Inf, scheduledBefore]. Default value is None.
- :paramtype scheduled_before: Optional[~datetime.datetime]
-
- :keyword scheduled_after: If specified, filter on jobs that was scheduled at or
- after given value. Range: [scheduledAfter, +Inf). Default value is None.
- :paramtype scheduled_after: Optional[~datetime.datetime]
-
-
- :keyword Optional[int] results_per_page: The maximum number of results to be returned per page.
-
- :return: An iterator like instance of RouterJob
- :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterJob]
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START list_jobs_async]
- :end-before: [END list_jobs_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve jobs
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START list_jobs_batched_async]
- :end-before: [END list_jobs_batched_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve jobs in batches
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START list_scheduled_jobs_async]
- :end-before: [END list_scheduled_jobs_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to retrieve scheduled jobs
- """
- if scheduled_before is not None and isinstance(scheduled_before, str):
- scheduled_before = _convert_str_to_datetime(scheduled_before)
-
- if scheduled_after is not None and isinstance(scheduled_after, str):
- scheduled_after = _convert_str_to_datetime(scheduled_after)
-
- return super().list_jobs(
- maxpagesize=results_per_page,
- status=status,
- channel_id=channel_id,
- queue_id=queue_id,
- classification_policy_id=classification_policy_id,
- scheduled_before=scheduled_before,
- scheduled_after=scheduled_after,
- **kwargs
- )
-
- @distributed_trace_async
- async def reclassify_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=arguments-differ
- """Reclassify a job.
-
- :param str job_id: Id of the job.
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START reclassify_job_async]
- :end-before: [END reclassify_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to re-classify a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- await super()._reclassify_job(job_id=job_id, options={}, **kwargs)
-
- @distributed_trace_async
- async def cancel_job(
- self, job_id: str, options: Optional[Union[_models._models.CancelJobOptions, JSON, IO]] = None, **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Closes a completed job.
-
- :param str job_id: Id of the job.
-
- :param options: Request model for cancelling job. Is one of the following types:
- CancelJobOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CancelJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START cancel_job_async]
- :end-before: [END cancel_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to cancel a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- await super()._cancel_job(job_id=job_id, options=options, **kwargs)
-
- @distributed_trace_async
- async def complete_job(
- self,
- job_id: str,
- assignment_id: str,
- options: Optional[Union[_models._models.CompleteJobOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Completes an assigned job.
-
- :param str job_id: Id of the job.
-
- :param assignment_id: The Id of the job assignment. Required.
- :type assignment_id: str
-
- :param options: Request model for completing job. Is one of the following types:
- CompleteJobOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CompleteJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START complete_job_async]
- :end-before: [END complete_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to complete a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- if not assignment_id:
- raise ValueError("assignment_id cannot be None.")
-
- await super()._complete_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs)
-
- @distributed_trace_async
- async def close_job(
- self,
- job_id: str,
- assignment_id: str,
- options: Optional[Union[_models._models.CloseJobOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Closes a completed job.
-
- :param str job_id: Id of the job.
-
- :param assignment_id: The Id of the job assignment. Required.
- :type assignment_id: str
-
- :param options: Request model for closing job. Is one of the following types: CloseJobOptions,
- JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.CloseJobOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START close_job_async]
- :end-before: [END close_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to close a job
- """
- if not job_id:
- raise ValueError("job_id cannot be None.")
-
- if not assignment_id:
- raise ValueError("assignment_id cannot be None.")
-
- await super()._close_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs)
-
- # endregion Job
-
- # region Offer
- @distributed_trace_async
- async def decline_job_offer(
- self,
- worker_id: str,
- offer_id: str,
- options: Optional[Union[_models._models.DeclineJobOfferOptions, JSON, IO]] = None,
- **kwargs: Any
- ) -> None: # pylint: disable=arguments-differ
- """Declines an offer to work on a job.
-
- :param worker_id: Id of the worker. Required.
- :type worker_id: str
- :param offer_id: Id of the offer. Required.
- :type offer_id: str
- :param options: Request model for declining offer. Is one of the following types:
- DeclineJobOfferOptions, JSON, IO Default value is None.
- :type options: ~azure.communication.jobrouter.models.DeclineJobOfferOptions or JSON or IO
-
- :return: None
- :rtype: None
- :raises: ~azure.core.exceptions.HttpResponseError, ValueError
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/router_job_crud_ops_async.py
- :start-after: [START close_job_async]
- :end-before: [END close_job_async]
- :language: python
- :dedent: 8
- :caption: Use a JobRouterClient to close a job
- """
- if not worker_id:
- raise ValueError("worker_id cannot be None.")
-
- if not offer_id:
- raise ValueError("offer_id cannot be None.")
-
- await super()._decline_job_offer(worker_id=worker_id, offer_id=offer_id, options=options, **kwargs)
-
- # endregion Offer
-
-
-__all__: List[str] = [
- "JobRouterClientOperationsMixin",
- "JobRouterAdministrationClientOperationsMixin",
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py
index 299ff2881418..f7dd32510333 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py
@@ -6,156 +6,9 @@
Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize
"""
-from typing import (
- List,
- Any,
-)
-from urllib.parse import urlparse
-from azure.core.credentials import AzureKeyCredential
-from .._shared.utils import parse_connection_str
-from .._shared.policy import HMACCredentialsPolicy
-from ._client import (
- JobRouterClient as JobRouterClientGenerated,
- JobRouterAdministrationClient as JobRouterAdministrationClientGenerated,
-)
-from .._api_versions import DEFAULT_VERSION
+from typing import List
-
-class JobRouterClient(JobRouterClientGenerated):
- """A client to interact with the AzureCommunicationService JobRouter service.
-
- This client provides operations to create and update jobs, policies and workers.
-
- :param str endpoint:
- The endpoint of the Azure Communication resource.
- :param ~azure.core.credentials.AzureKeyCredential credential:
- The credentials with which to authenticate
-
- :keyword api_version: Azure Communication Job Router API version.
- Default value is "2023-11-01".
- Note that overriding this default value may result in unsupported behavior.
- """
-
- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None:
- if not credential:
- raise ValueError("credential can not be None")
-
- # TokenCredential not supported at the moment
- if hasattr(credential, "get_token"):
- raise TypeError(
- "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy"
- " for authentication".format(type(credential))
- )
-
- try:
- if not endpoint.lower().startswith("http"):
- endpoint = "https://" + endpoint
- except AttributeError:
- raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from
-
- parsed_url = urlparse(endpoint.rstrip("/"))
- if not parsed_url.netloc:
- raise ValueError("Invalid URL: {}".format(endpoint))
-
- self._endpoint = endpoint
- self._api_version = kwargs.pop("api_version", DEFAULT_VERSION)
- self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key)
- super().__init__(
- self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs
- )
-
- @classmethod
- def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterClient":
- """Create JobRouterClient from a Connection String.
-
- :param str conn_str:
- A connection string to an Azure Communication Service resource.
- :return: Instance of JobRouterClient.
- :rtype: ~azure.communication.jobrouter.aio.JobRouterClient
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/sample_authentication_async.py
- :start-after: [START auth_from_connection_string_async]
- :end-before: [END auth_from_connection_string_async]
- :language: python
- :dedent: 8
- :caption: Authenticating a JobRouterClient from a connection_string
- """
- endpoint, access_key = parse_connection_str(conn_str)
- return cls(endpoint, AzureKeyCredential(access_key), **kwargs)
-
-
-class JobRouterAdministrationClient(JobRouterAdministrationClientGenerated):
- """A client to interact with the AzureCommunicationService JobRouter service.
-
- This client provides operations to create, update, list and delete the following entities: classification policy,
- exception policy, distribution policy and queue.
-
- :param str endpoint:
- The endpoint of the Azure Communication resource.
- :param ~azure.core.credentials.AzureKeyCredential credential:
- The credentials with which to authenticate
-
- :keyword api_version: Azure Communication Job Router API version. Default value is "2023-11-01".
- Note that overriding this default value may result in unsupported behavior.
- :paramtype api_version: str
- """
-
- def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> "None":
- if not credential:
- raise ValueError("credential can not be None")
-
- # TokenCredential not supported at the moment
- if hasattr(credential, "get_token"):
- raise TypeError(
- "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy"
- " for authentication".format(type(credential))
- )
-
- try:
- if not endpoint.lower().startswith("http"):
- endpoint = "https://" + endpoint
- except AttributeError:
- raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from
-
- parsed_url = urlparse(endpoint.rstrip("/"))
- if not parsed_url.netloc:
- raise ValueError("Invalid URL: {}".format(endpoint))
-
- self._endpoint = endpoint
- self._api_version = kwargs.pop("api_version", DEFAULT_VERSION)
- self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key)
- super().__init__(
- self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs
- )
-
- @classmethod
- def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterAdministrationClient":
- """Create JobRouterClient from a Connection String.
-
- :param str conn_str:
- A connection string to an Azure Communication Service resource.
- :return: Instance of JobRouterAdministrationClient.
- :rtype: ~azure.communication.jobrouter.aio.JobRouterAdministrationClient
-
- .. admonition:: Example:
-
- .. literalinclude:: ../samples/sample_authentication_async.py
- :start-after: [START admin_auth_from_connection_string_async]
- :end-before: [END admin_auth_from_connection_string_async]
- :language: python
- :dedent: 8
- :caption: Authenticating a JobRouterAdministrationClient from a connection_string
- """
- endpoint, access_key = parse_connection_str(conn_str)
- return cls(endpoint, AzureKeyCredential(access_key), **kwargs)
-
-
-__all__: List[str] = [
- "JobRouterClient",
- "JobRouterAdministrationClient",
-] # Add all objects you want publicly available to users at this package level
+__all__: List[str] = [] # Add all objects you want publicly available to users at this package level
def patch_sdk():
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py
index 8a2a6db2ca5a..0705bd033f58 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py
@@ -13,7 +13,6 @@
from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from azure.core import AsyncPipelineClient
from .._serialization import Deserializer, Serializer
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py
index f81170a6f9e0..c56418d48dd3 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py
@@ -5,86 +5,102 @@
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=wrong-import-position
-from ._models import AcceptJobOfferResult
-from ._models import BestWorkerMode
-from ._models import CancelExceptionAction
-from ._models import CancelJobOptions
-from ._models import ClassificationPolicy
-from ._models import CloseJobOptions
-from ._models import CompleteJobOptions
-from ._models import ConditionalQueueSelectorAttachment
-from ._models import ConditionalWorkerSelectorAttachment
-from ._models import DeclineJobOfferOptions
-from ._models import DirectMapRouterRule
-from ._models import DistributionMode
-from ._models import DistributionPolicy
-from ._models import ExceptionAction
-from ._models import ExceptionPolicy
-from ._models import ExceptionRule
-from ._models import ExceptionTrigger
-from ._models import ExpressionRouterRule
-from ._models import FunctionRouterRule
-from ._models import FunctionRouterRuleCredential
-from ._models import JobMatchingMode
-from ._models import LongestIdleMode
-from ._models import ManualReclassifyExceptionAction
-from ._models import OAuth2WebhookClientCredential
-from ._models import PassThroughQueueSelectorAttachment
-from ._models import PassThroughWorkerSelectorAttachment
-from ._models import QueueAndMatchMode
-from ._models import QueueLengthExceptionTrigger
-from ._models import QueueSelectorAttachment
-from ._models import QueueWeightedAllocation
-from ._models import ReclassifyExceptionAction
-from ._models import RoundRobinMode
-from ._models import RouterChannel
-from ._models import RouterJob
-from ._models import RouterJobAssignment
-from ._models import RouterJobNote
-from ._models import RouterJobOffer
-from ._models import RouterJobPositionDetails
-from ._models import RouterQueue
-from ._models import RouterQueueSelector
-from ._models import RouterQueueStatistics
-from ._models import RouterRule
-from ._models import RouterWorker
-from ._models import RouterWorkerAssignment
-from ._models import RouterWorkerSelector
-from ._models import RuleEngineQueueSelectorAttachment
-from ._models import RuleEngineWorkerSelectorAttachment
-from ._models import ScheduleAndSuspendMode
-from ._models import ScoringRuleOptions
-from ._models import StaticQueueSelectorAttachment
-from ._models import StaticRouterRule
-from ._models import StaticWorkerSelectorAttachment
-from ._models import SuspendMode
-from ._models import UnassignJobOptions
-from ._models import UnassignJobResult
-from ._models import WaitTimeExceptionTrigger
-from ._models import WebhookRouterRule
-from ._models import WeightedAllocationQueueSelectorAttachment
-from ._models import WeightedAllocationWorkerSelectorAttachment
-from ._models import WorkerSelectorAttachment
-from ._models import WorkerWeightedAllocation
+from typing import TYPE_CHECKING
-from ._enums import DistributionModeKind
-from ._enums import ExceptionActionKind
-from ._enums import ExceptionTriggerKind
-from ._enums import ExpressionRouterRuleLanguage
-from ._enums import JobMatchingModeKind
-from ._enums import LabelOperator
-from ._enums import QueueSelectorAttachmentKind
-from ._enums import RouterJobStatus
-from ._enums import RouterJobStatusSelector
-from ._enums import RouterRuleKind
-from ._enums import RouterWorkerSelectorStatus
-from ._enums import RouterWorkerState
-from ._enums import RouterWorkerStateSelector
-from ._enums import ScoringRuleParameterSelector
-from ._enums import WorkerSelectorAttachmentKind
+if TYPE_CHECKING:
+ from ._patch import * # pylint: disable=unused-wildcard-import
+
+
+from ._models import ( # type: ignore
+ AcceptJobOfferResult,
+ BestWorkerMode,
+ CancelExceptionAction,
+ CancelJobOptions,
+ CancelJobResult,
+ ClassificationPolicy,
+ CloseJobOptions,
+ CloseJobResult,
+ CompleteJobOptions,
+ CompleteJobResult,
+ ConditionalQueueSelectorAttachment,
+ ConditionalWorkerSelectorAttachment,
+ DeclineJobOfferOptions,
+ DeclineJobOfferResult,
+ DirectMapRouterRule,
+ DistributionMode,
+ DistributionPolicy,
+ ExceptionAction,
+ ExceptionPolicy,
+ ExceptionRule,
+ ExceptionTrigger,
+ ExpressionRouterRule,
+ FunctionRouterRule,
+ FunctionRouterRuleCredential,
+ JobMatchingMode,
+ LongestIdleMode,
+ ManualReclassifyExceptionAction,
+ OAuth2WebhookClientCredential,
+ PassThroughQueueSelectorAttachment,
+ PassThroughWorkerSelectorAttachment,
+ QueueAndMatchMode,
+ QueueLengthExceptionTrigger,
+ QueueSelectorAttachment,
+ QueueWeightedAllocation,
+ ReclassifyExceptionAction,
+ ReclassifyJobResult,
+ RoundRobinMode,
+ RouterChannel,
+ RouterJob,
+ RouterJobAssignment,
+ RouterJobNote,
+ RouterJobOffer,
+ RouterJobPositionDetails,
+ RouterQueue,
+ RouterQueueSelector,
+ RouterQueueStatistics,
+ RouterRule,
+ RouterWorker,
+ RouterWorkerAssignment,
+ RouterWorkerSelector,
+ RuleEngineQueueSelectorAttachment,
+ RuleEngineWorkerSelectorAttachment,
+ ScheduleAndSuspendMode,
+ ScoringRuleOptions,
+ StaticQueueSelectorAttachment,
+ StaticRouterRule,
+ StaticWorkerSelectorAttachment,
+ SuspendMode,
+ UnassignJobOptions,
+ UnassignJobResult,
+ WaitTimeExceptionTrigger,
+ WebhookRouterRule,
+ WeightedAllocationQueueSelectorAttachment,
+ WeightedAllocationWorkerSelectorAttachment,
+ WorkerSelectorAttachment,
+ WorkerWeightedAllocation,
+)
+
+from ._enums import ( # type: ignore
+ DistributionModeKind,
+ ExceptionActionKind,
+ ExceptionTriggerKind,
+ ExpressionRouterRuleLanguage,
+ JobMatchingModeKind,
+ LabelOperator,
+ QueueSelectorAttachmentKind,
+ RouterJobStatus,
+ RouterJobStatusSelector,
+ RouterRuleKind,
+ RouterWorkerSelectorStatus,
+ RouterWorkerState,
+ RouterWorkerStateSelector,
+ ScoringRuleParameterSelector,
+ WorkerSelectorAttachmentKind,
+)
from ._patch import __all__ as _patch_all
-from ._patch import * # pylint: disable=unused-wildcard-import
+from ._patch import *
from ._patch import patch_sdk as _patch_sdk
__all__ = [
@@ -92,12 +108,16 @@
"BestWorkerMode",
"CancelExceptionAction",
"CancelJobOptions",
+ "CancelJobResult",
"ClassificationPolicy",
"CloseJobOptions",
+ "CloseJobResult",
"CompleteJobOptions",
+ "CompleteJobResult",
"ConditionalQueueSelectorAttachment",
"ConditionalWorkerSelectorAttachment",
"DeclineJobOfferOptions",
+ "DeclineJobOfferResult",
"DirectMapRouterRule",
"DistributionMode",
"DistributionPolicy",
@@ -119,6 +139,7 @@
"QueueSelectorAttachment",
"QueueWeightedAllocation",
"ReclassifyExceptionAction",
+ "ReclassifyJobResult",
"RoundRobinMode",
"RouterChannel",
"RouterJob",
@@ -165,5 +186,5 @@
"ScoringRuleParameterSelector",
"WorkerSelectorAttachmentKind",
]
-__all__.extend([p for p in _patch_all if p not in __all__])
+__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore
_patch_sdk()
diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py
index 746ee8a85300..ae0bfc2c0763 100644
--- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py
+++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py
@@ -1,11 +1,12 @@
+# pylint: disable=too-many-lines
# coding=utf-8
-# pylint: disable=too-many-lines,anomalous-backslash-in-string,name-too-long
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) Python Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
+# pylint: disable=useless-super-delegation
import datetime
from typing import Any, Dict, List, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload
@@ -23,14 +24,12 @@
)
if TYPE_CHECKING:
- # pylint: disable=unused-import,ungrouped-imports
from .. import models as _models
class AcceptJobOfferResult(_model_base.Model):
"""Response containing ids for the worker, job, and assignment from an accepted offer.
- All required parameters must be populated in order to send to server.
:ivar assignment_id: Id of job assignment that assigns a worker that has accepted an offer to a
job. Required.
@@ -55,17 +54,16 @@ def __init__(
assignment_id: str,
job_id: str,
worker_id: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -75,7 +73,6 @@ class DistributionMode(_model_base.Model):
You probably want to use the sub-classes and not this class directly. Known sub-classes are:
BestWorkerMode, LongestIdleMode, RoundRobinMode
- All required parameters must be populated in order to send to server.
:ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a
job can have.
@@ -115,24 +112,22 @@ def __init__(
min_concurrent_offers: Optional[int] = None,
max_concurrent_offers: Optional[int] = None,
bypass_selectors: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class BestWorkerMode(DistributionMode, discriminator="bestWorker"):
"""Jobs are distributed to the worker with the strongest abilities available.
- All required parameters must be populated in order to send to server.
:ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a
job can have.
@@ -178,17 +173,16 @@ def __init__(
bypass_selectors: Optional[bool] = None,
scoring_rule: Optional["_models.RouterRule"] = None,
scoring_rule_options: Optional["_models.ScoringRuleOptions"] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=DistributionModeKind.BEST_WORKER, **kwargs)
@@ -198,7 +192,6 @@ class ExceptionAction(_model_base.Model):
You probably want to use the sub-classes and not this class directly. Known sub-classes are:
CancelExceptionAction, ManualReclassifyExceptionAction, ReclassifyExceptionAction
- All required parameters must be populated in order to send to server.
:ivar id: Unique Id of the exception action.
:vartype id: str
@@ -220,24 +213,22 @@ def __init__(
*,
kind: str,
id: Optional[str] = None, # pylint: disable=redefined-builtin
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class CancelExceptionAction(ExceptionAction, discriminator="cancel"):
"""An action that marks a job as cancelled.
- All required parameters must be populated in order to send to server.
:ivar id: Unique Id of the exception action.
:vartype id: str
@@ -267,17 +258,16 @@ def __init__(
id: Optional[str] = None, # pylint: disable=redefined-builtin
note: Optional[str] = None,
disposition_code: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=ExceptionActionKind.CANCEL, **kwargs)
@@ -304,17 +294,16 @@ def __init__(
*,
note: Optional[str] = None,
disposition_code: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -327,7 +316,6 @@ class ClassificationPolicy(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -377,17 +365,16 @@ def __init__(
queue_selector_attachments: Optional[List["_models.QueueSelectorAttachment"]] = None,
prioritization_rule: Optional["_models.RouterRule"] = None,
worker_selector_attachments: Optional[List["_models.WorkerSelectorAttachment"]] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -422,17 +409,16 @@ def __init__(
disposition_code: Optional[str] = None,
close_at: Optional[datetime.datetime] = None,
note: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -456,17 +442,16 @@ def __init__(
self,
*,
note: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -482,7 +467,6 @@ class QueueSelectorAttachment(_model_base.Model):
RuleEngineQueueSelectorAttachment, StaticQueueSelectorAttachment,
WeightedAllocationQueueSelectorAttachment
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of QueueSelectorAttachment. Required.
Known values are: "conditional", "passThrough", "ruleEngine", "static", and
@@ -500,17 +484,16 @@ def __init__(
self,
*,
kind: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -518,7 +501,6 @@ class ConditionalQueueSelectorAttachment(QueueSelectorAttachment, discriminator=
"""Describes a set of queue selectors that will be attached if the given condition resolves to
true.
- All required parameters must be populated in order to send to server.
:ivar condition: The condition that must be true for the queue selectors to be attached.
Required.
@@ -544,17 +526,16 @@ def __init__(
*,
condition: "_models.RouterRule",
queue_selectors: List["_models.RouterQueueSelector"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=QueueSelectorAttachmentKind.CONDITIONAL, **kwargs)
@@ -566,7 +547,6 @@ class WorkerSelectorAttachment(_model_base.Model):
RuleEngineWorkerSelectorAttachment, StaticWorkerSelectorAttachment,
WeightedAllocationWorkerSelectorAttachment
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of WorkerSelectorAttachment. Required.
Known values are: "conditional", "passThrough", "ruleEngine", "static", and
@@ -585,17 +565,16 @@ def __init__(
self,
*,
kind: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -603,7 +582,6 @@ class ConditionalWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato
"""Describes a set of worker selectors that will be attached if the given condition resolves to
true.
- All required parameters must be populated in order to send to server.
:ivar condition: The condition that must be true for the worker selectors to be attached.
Required.
@@ -629,17 +607,16 @@ def __init__(
*,
condition: "_models.RouterRule",
worker_selectors: List["_models.RouterWorkerSelector"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=WorkerSelectorAttachmentKind.CONDITIONAL, **kwargs)
@@ -665,17 +642,16 @@ def __init__(
self,
*,
retry_offer_at: Optional[datetime.datetime] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -697,7 +673,6 @@ class RouterRule(_model_base.Model):
DirectMapRouterRule, ExpressionRouterRule, FunctionRouterRule, StaticRouterRule,
WebhookRouterRule
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of RouterRule. Required. Known values
are: "directMap", "expression", "function", "static", and "webhook".
@@ -714,24 +689,22 @@ def __init__(
self,
*,
kind: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class DirectMapRouterRule(RouterRule, discriminator="directMap"):
"""A rule that return the same labels as the input labels.
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of Rule. Required. Discriminator value
for DirectMapRouterRule.
@@ -742,13 +715,27 @@ class DirectMapRouterRule(RouterRule, discriminator="directMap"):
"""The type discriminator describing a sub-type of Rule. Required. Discriminator value for
DirectMapRouterRule."""
+ @overload
+ def __init__(
+ self,
+ ) -> None: ...
+
+ @overload
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
+ """
+ :param mapping: raw JSON to initialize the model.
+ :type mapping: Mapping[str, Any]
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, kind=RouterRuleKind.DIRECT_MAP, **kwargs)
+
class DistributionPolicy(_model_base.Model):
"""Policy governing how jobs are distributed to workers.
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -781,17 +768,16 @@ def __init__(
name: Optional[str] = None,
offer_expires_after_seconds: Optional[float] = None,
mode: Optional["_models.DistributionMode"] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -800,7 +786,6 @@ class ExceptionPolicy(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -827,24 +812,22 @@ def __init__(
*,
name: Optional[str] = None,
exception_rules: Optional[List["_models.ExceptionRule"]] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class ExceptionRule(_model_base.Model):
"""A rule that defines actions to execute upon a specific trigger.
- All required parameters must be populated in order to send to server.
:ivar id: Id of an exception rule. Required.
:vartype id: str
@@ -868,17 +851,16 @@ def __init__(
id: str, # pylint: disable=redefined-builtin
trigger: "_models.ExceptionTrigger",
actions: List["_models.ExceptionAction"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -888,7 +870,6 @@ class ExceptionTrigger(_model_base.Model):
You probably want to use the sub-classes and not this class directly. Known sub-classes are:
QueueLengthExceptionTrigger, WaitTimeExceptionTrigger
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of ExceptionTrigger. Required. Known
values are: "queueLength" and "waitTime".
@@ -905,24 +886,22 @@ def __init__(
self,
*,
kind: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class ExpressionRouterRule(RouterRule, discriminator="expression"):
"""A rule providing inline expression rules.
- All required parameters must be populated in order to send to server.
:ivar language: The expression language to compile to and execute. "powerFx"
:vartype language: str or ~azure.communication.jobrouter.models.ExpressionRouterRuleLanguage
@@ -948,24 +927,22 @@ def __init__(
*,
expression: str,
language: Optional[Union[str, "_models.ExpressionRouterRuleLanguage"]] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=RouterRuleKind.EXPRESSION, **kwargs)
class FunctionRouterRule(RouterRule, discriminator="function"):
"""A rule providing a binding to an HTTP Triggered Azure Function.
- All required parameters must be populated in order to send to server.
:ivar function_uri: URL for Azure Function. Required.
:vartype function_uri: str
@@ -990,17 +967,16 @@ def __init__(
*,
function_uri: str,
credential: Optional["_models.FunctionRouterRuleCredential"] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=RouterRuleKind.FUNCTION, **kwargs)
@@ -1033,17 +1009,16 @@ def __init__(
function_key: Optional[str] = None,
app_key: Optional[str] = None,
client_id: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1058,7 +1033,6 @@ class JobMatchingMode(_model_base.Model):
You probably want to use the sub-classes and not this class directly. Known sub-classes are:
QueueAndMatchMode, ScheduleAndSuspendMode, SuspendMode
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing a sub-type of JobMatchingMode. Required. Known
values are: "queueAndMatch", "scheduleAndSuspend", and "suspend".
@@ -1075,24 +1049,22 @@ def __init__(
self,
*,
kind: str,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class LongestIdleMode(DistributionMode, discriminator="longestIdle"):
"""Jobs are directed to the worker who has been idle longest.
- All required parameters must be populated in order to send to server.
:ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a
job can have.
@@ -1121,17 +1093,16 @@ def __init__(
min_concurrent_offers: Optional[int] = None,
max_concurrent_offers: Optional[int] = None,
bypass_selectors: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=DistributionModeKind.LONGEST_IDLE, **kwargs)
@@ -1139,7 +1110,6 @@ class ManualReclassifyExceptionAction(ExceptionAction, discriminator="manualRecl
"""An action that manually reclassifies a job by providing the queue, priority and worker
selectors.
- All required parameters must be populated in order to send to server.
:ivar id: Unique Id of the exception action.
:vartype id: str
@@ -1172,17 +1142,16 @@ def __init__(
queue_id: Optional[str] = None,
priority: Optional[int] = None,
worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=ExceptionActionKind.MANUAL_RECLASSIFY, **kwargs)
@@ -1207,17 +1176,16 @@ def __init__(
*,
client_id: Optional[str] = None,
client_secret: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1225,7 +1193,6 @@ class PassThroughQueueSelectorAttachment(QueueSelectorAttachment, discriminator=
"""Attaches a queue selector where the value is passed through from a job's label with the same
key.
- All required parameters must be populated in order to send to server.
:ivar key: The label key to query against. Required.
:vartype key: str
@@ -1254,17 +1221,16 @@ def __init__(
*,
key: str,
label_operator: Union[str, "_models.LabelOperator"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=QueueSelectorAttachmentKind.PASS_THROUGH, **kwargs)
@@ -1272,7 +1238,6 @@ class PassThroughWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato
"""Attaches a worker selector where the value is passed through from a job's label with the same
key.
- All required parameters must be populated in order to send to server.
:ivar key: The label key to query against. Required.
:vartype key: str
@@ -1307,17 +1272,16 @@ def __init__(
key: str,
label_operator: Union[str, "_models.LabelOperator"],
expires_after_seconds: Optional[float] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=WorkerSelectorAttachmentKind.PASS_THROUGH, **kwargs)
@@ -1325,7 +1289,6 @@ class QueueAndMatchMode(JobMatchingMode, discriminator="queueAndMatch"):
"""Describes a matching mode where matching worker to a job is automatically started after job is
queued successfully.
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing QueueAndMatchMode. Required. Discriminator value
for QueueAndMatchMode.
@@ -1336,11 +1299,25 @@ class QueueAndMatchMode(JobMatchingMode, discriminator="queueAndMatch"):
"""The type discriminator describing QueueAndMatchMode. Required. Discriminator value for
QueueAndMatchMode."""
+ @overload
+ def __init__(
+ self,
+ ) -> None: ...
+
+ @overload
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
+ """
+ :param mapping: raw JSON to initialize the model.
+ :type mapping: Mapping[str, Any]
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, kind=JobMatchingModeKind.QUEUE_AND_MATCH, **kwargs)
+
class QueueLengthExceptionTrigger(ExceptionTrigger, discriminator="queueLength"):
"""Trigger for an exception action on exceeding queue length.
- All required parameters must be populated in order to send to server.
:ivar threshold: Threshold of number of jobs ahead in the queue to for this trigger to fire.
Required.
@@ -1361,17 +1338,16 @@ def __init__(
self,
*,
threshold: int,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=ExceptionTriggerKind.QUEUE_LENGTH, **kwargs)
@@ -1379,7 +1355,6 @@ class QueueWeightedAllocation(_model_base.Model):
"""Contains the weight percentage and queue selectors to be applied if selected for weighted
distributions.
- All required parameters must be populated in order to send to server.
:ivar weight: The percentage of this weight, expressed as a fraction of 1. Required.
:vartype weight: float
@@ -1399,24 +1374,22 @@ def __init__(
*,
weight: float,
queue_selectors: List["_models.RouterQueueSelector"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class ReclassifyExceptionAction(ExceptionAction, discriminator="reclassify"):
"""An action that modifies labels on a job and then reclassifies it.
- All required parameters must be populated in order to send to server.
:ivar id: Unique Id of the exception action.
:vartype id: str
@@ -1447,17 +1420,16 @@ def __init__(
id: Optional[str] = None, # pylint: disable=redefined-builtin
classification_policy_id: Optional[str] = None,
labels_to_upsert: Optional[Dict[str, Any]] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=ExceptionActionKind.RECLASSIFY, **kwargs)
@@ -1473,7 +1445,6 @@ class RoundRobinMode(DistributionMode, discriminator="roundRobin"):
"""Jobs are distributed in order to workers, starting with the worker that is after the last
worker to receive a job.
- All required parameters must be populated in order to send to server.
:ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a
job can have.
@@ -1502,24 +1473,22 @@ def __init__(
min_concurrent_offers: Optional[int] = None,
max_concurrent_offers: Optional[int] = None,
bypass_selectors: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=DistributionModeKind.ROUND_ROBIN, **kwargs)
class RouterChannel(_model_base.Model):
"""Represents the capacity a job in this channel will consume from a worker.
- All required parameters must be populated in order to send to server.
:ivar channel_id: Id of a channel. Required.
:vartype channel_id: str
@@ -1527,7 +1496,7 @@ class RouterChannel(_model_base.Model):
will consume of the total worker capacity. Required.
:vartype capacity_cost_per_job: int
:ivar max_number_of_jobs: The maximum number of jobs that can be supported concurrently for
- this channel.
+ this channel. Value must be greater than zero.
:vartype max_number_of_jobs: int
"""
@@ -1537,7 +1506,8 @@ class RouterChannel(_model_base.Model):
"""The amount of capacity that an instance of a job of this channel will consume of the total
worker capacity. Required."""
max_number_of_jobs: Optional[int] = rest_field(name="maxNumberOfJobs")
- """The maximum number of jobs that can be supported concurrently for this channel."""
+ """The maximum number of jobs that can be supported concurrently for this channel. Value must be
+ greater than zero."""
@overload
def __init__(
@@ -1546,26 +1516,24 @@ def __init__(
channel_id: str,
capacity_cost_per_job: int,
max_number_of_jobs: Optional[int] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
-class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attributes
+class RouterJob(_model_base.Model):
"""A unit of work to be routed.
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -1585,7 +1553,7 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu
:vartype classification_policy_id: str
:ivar queue_id: Id of a queue that this job is queued to.
:vartype queue_id: str
- :ivar priority: Priority of this job.
+ :ivar priority: Priority of this job. Value must be between -100 to 100.
:vartype priority: int
:ivar disposition_code: Reason code for cancelled or closed jobs.
:vartype disposition_code: str
@@ -1633,7 +1601,7 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu
queue_id: Optional[str] = rest_field(name="queueId")
"""Id of a queue that this job is queued to."""
priority: Optional[int] = rest_field()
- """Priority of this job."""
+ """Priority of this job. Value must be between -100 to 100."""
disposition_code: Optional[str] = rest_field(name="dispositionCode")
"""Reason code for cancelled or closed jobs."""
requested_worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = rest_field(
@@ -1677,17 +1645,16 @@ def __init__(
tags: Optional[Dict[str, Any]] = None,
notes: Optional[List["_models.RouterJobNote"]] = None,
matching_mode: Optional["_models.JobMatchingMode"] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1696,7 +1663,6 @@ class RouterJobAssignment(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar assignment_id: Id of a job assignment. Required.
:vartype assignment_id: str
@@ -1729,24 +1695,22 @@ def __init__(
worker_id: Optional[str] = None,
completed_at: Optional[datetime.datetime] = None,
closed_at: Optional[datetime.datetime] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RouterJobNote(_model_base.Model):
"""A note attached to a job.
- All required parameters must be populated in order to send to server.
:ivar message: The message contained in the note. Required.
:vartype message: str
@@ -1766,17 +1730,16 @@ def __init__(
*,
message: str,
added_at: Optional[datetime.datetime] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1785,7 +1748,6 @@ class RouterJobOffer(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar offer_id: Id of an offer. Required.
:vartype offer_id: str
@@ -1818,24 +1780,22 @@ def __init__(
capacity_cost: int,
offered_at: Optional[datetime.datetime] = None,
expires_at: Optional[datetime.datetime] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RouterJobPositionDetails(_model_base.Model):
"""Position and estimated wait time for a job.
- All required parameters must be populated in order to send to server.
:ivar job_id: Id of the job these details are about. Required.
:vartype job_id: str
@@ -1870,17 +1830,16 @@ def __init__(
queue_id: str,
queue_length: int,
estimated_wait_time_minutes: float,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -1889,7 +1848,6 @@ class RouterQueue(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -1930,24 +1888,22 @@ def __init__(
distribution_policy_id: Optional[str] = None,
labels: Optional[Dict[str, Any]] = None,
exception_policy_id: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RouterQueueSelector(_model_base.Model):
"""Describes a condition that must be met against a set of labels for queue selection.
- All required parameters must be populated in order to send to server.
:ivar key: The label key to query against. Required.
:vartype key: str
@@ -1977,24 +1933,22 @@ def __init__(
key: str,
label_operator: Union[str, "_models.LabelOperator"],
value: Optional[Any] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RouterQueueStatistics(_model_base.Model):
"""Statistics for the queue.
- All required parameters must be populated in order to send to server.
:ivar queue_id: Id of the queue these details are about. Required.
:vartype queue_id: str
@@ -2026,26 +1980,24 @@ def __init__(
length: int,
estimated_wait_time_minutes: Optional[Dict[str, float]] = None,
longest_job_wait_time_minutes: Optional[float] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
-class RouterWorker(_model_base.Model): # pylint: disable=too-many-instance-attributes
+class RouterWorker(_model_base.Model):
"""An entity for jobs to be routed to.
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar etag: The entity tag for this resource. Required.
:vartype etag: str
@@ -2123,24 +2075,22 @@ def __init__(
channels: Optional[List["_models.RouterChannel"]] = None,
available_for_offers: Optional[bool] = None,
max_concurrent_offers: Optional[int] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RouterWorkerAssignment(_model_base.Model):
"""The assignment for a worker to a job.
- All required parameters must be populated in order to send to server.
:ivar assignment_id: Id of the assignment. Required.
:vartype assignment_id: str
@@ -2170,17 +2120,16 @@ def __init__(
job_id: str,
capacity_cost: int,
assigned_at: datetime.datetime,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@@ -2189,7 +2138,6 @@ class RouterWorkerSelector(_model_base.Model):
Readonly variables are only populated by the server, and will be ignored when sending a request.
- All required parameters must be populated in order to send to server.
:ivar key: The label key to query against. Required.
:vartype key: str
@@ -2237,24 +2185,22 @@ def __init__(
value: Optional[Any] = None,
expires_after_seconds: Optional[float] = None,
expedite: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class RuleEngineQueueSelectorAttachment(QueueSelectorAttachment, discriminator="ruleEngine"):
"""Attaches queue selectors to a job when the RouterRule is resolved.
- All required parameters must be populated in order to send to server.
:ivar rule: A RouterRule that resolves a collection of queue selectors to attach. Required.
:vartype rule: ~azure.communication.jobrouter.models.RouterRule
@@ -2274,24 +2220,22 @@ def __init__(
self,
*,
rule: "_models.RouterRule",
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=QueueSelectorAttachmentKind.RULE_ENGINE, **kwargs)
class RuleEngineWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator="ruleEngine"):
"""Attaches worker selectors to a job when a RouterRule is resolved.
- All required parameters must be populated in order to send to server.
:ivar rule: A RouterRule that resolves a collection of worker selectors to attach. Required.
:vartype rule: ~azure.communication.jobrouter.models.RouterRule
@@ -2311,17 +2255,16 @@ def __init__(
self,
*,
rule: "_models.RouterRule",
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=WorkerSelectorAttachmentKind.RULE_ENGINE, **kwargs)
@@ -2329,7 +2272,6 @@ class ScheduleAndSuspendMode(JobMatchingMode, discriminator="scheduleAndSuspend"
"""Describes a matching mode used for scheduling jobs to be queued at a future time. At the
specified time, matching worker to a job will not start automatically.
- All required parameters must be populated in order to send to server.
:ivar schedule_at: Requested schedule time. Required.
:vartype schedule_at: ~datetime.datetime
@@ -2349,17 +2291,16 @@ def __init__(
self,
*,
schedule_at: datetime.datetime,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=JobMatchingModeKind.SCHEDULE_AND_SUSPEND, **kwargs)
@@ -2370,9 +2311,9 @@ class ScoringRuleOptions(_model_base.Model):
not configured.
:vartype batch_size: int
:ivar scoring_parameters: List of extra parameters from a job that will be sent as part of the
- payload to scoring rule. If not set, a job's labels (sent in the payload as ``job``\ ) and a
- job's worker selectors (sent in the payload as ``selectors``\ ) are added to the payload of the
- scoring rule by default. Note: Worker labels are always sent with scoring payload.
+ payload to scoring rule. If not set, a job's labels (sent in the payload as ``job``\\ ) and a
+ job's worker selectors (sent in the payload as ``selectors``\\ ) are added to the payload of
+ the scoring rule by default. Note: Worker labels are always sent with scoring payload.
:vartype scoring_parameters: list[str or
~azure.communication.jobrouter.models.ScoringRuleParameterSelector]
:ivar is_batch_scoring_enabled: If set to true, will score workers in batches, and the
@@ -2408,24 +2349,22 @@ def __init__(
scoring_parameters: Optional[List[Union[str, "_models.ScoringRuleParameterSelector"]]] = None,
is_batch_scoring_enabled: Optional[bool] = None,
descending_order: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class StaticQueueSelectorAttachment(QueueSelectorAttachment, discriminator="static"):
"""Describes a queue selector that will be attached to a job.
- All required parameters must be populated in order to send to server.
:ivar queue_selector: The queue selector to attach. Required.
:vartype queue_selector: ~azure.communication.jobrouter.models.RouterQueueSelector
@@ -2445,24 +2384,22 @@ def __init__(
self,
*,
queue_selector: "_models.RouterQueueSelector",
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=QueueSelectorAttachmentKind.STATIC, **kwargs)
class StaticRouterRule(RouterRule, discriminator="static"):
"""A rule providing static rules that always return the same result, regardless of input.
- All required parameters must be populated in order to send to server.
:ivar value: The static value this rule always returns. Values must be primitive values -
number, string, boolean.
@@ -2484,24 +2421,22 @@ def __init__(
self,
*,
value: Optional[Any] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=RouterRuleKind.STATIC, **kwargs)
class StaticWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator="static"):
"""Describes a worker selector that will be attached to a job.
- All required parameters must be populated in order to send to server.
:ivar worker_selector: The worker selector to attach. Required.
:vartype worker_selector: ~azure.communication.jobrouter.models.RouterWorkerSelector
@@ -2521,24 +2456,22 @@ def __init__(
self,
*,
worker_selector: "_models.RouterWorkerSelector",
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=WorkerSelectorAttachmentKind.STATIC, **kwargs)
class SuspendMode(JobMatchingMode, discriminator="suspend"):
"""Describes a matching mode where matching worker to a job is suspended.
- All required parameters must be populated in order to send to server.
:ivar kind: The type discriminator describing SuspendMode. Required. Discriminator value for
SuspendMode.
@@ -2548,6 +2481,21 @@ class SuspendMode(JobMatchingMode, discriminator="suspend"):
kind: Literal[JobMatchingModeKind.SUSPEND] = rest_discriminator(name="kind") # type: ignore
"""The type discriminator describing SuspendMode. Required. Discriminator value for SuspendMode."""
+ @overload
+ def __init__(
+ self,
+ ) -> None: ...
+
+ @overload
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
+ """
+ :param mapping: raw JSON to initialize the model.
+ :type mapping: Mapping[str, Any]
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, kind=JobMatchingModeKind.SUSPEND, **kwargs)
+
class UnassignJobOptions(_model_base.Model):
"""Request payload for unassigning a job.
@@ -2565,24 +2513,22 @@ def __init__(
self,
*,
suspend_matching: Optional[bool] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class UnassignJobResult(_model_base.Model):
"""Response payload after a job has been successfully unassigned.
- All required parameters must be populated in order to send to server.
:ivar job_id: Id of an unassigned job. Required.
:vartype job_id: str
@@ -2601,24 +2547,22 @@ def __init__(
*,
job_id: str,
unassignment_count: int,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
class WaitTimeExceptionTrigger(ExceptionTrigger, discriminator="waitTime"):
"""Trigger for an exception action on exceeding wait time.
- All required parameters must be populated in order to send to server.
:ivar threshold_seconds: Threshold for wait time for this trigger. Required.
:vartype threshold_seconds: float
@@ -2638,24 +2582,22 @@ def __init__(
self,
*,
threshold_seconds: float,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=ExceptionTriggerKind.WAIT_TIME, **kwargs)
class WebhookRouterRule(RouterRule, discriminator="webhook"):
"""A rule providing a binding to an external web server.
- All required parameters must be populated in order to send to server.
:ivar authorization_server_uri: Uri for Authorization Server.
:vartype authorization_server_uri: str
@@ -2687,17 +2629,16 @@ def __init__(
authorization_server_uri: Optional[str] = None,
client_credential: Optional["_models.OAuth2WebhookClientCredential"] = None,
webhook_uri: Optional[str] = None,
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=RouterRuleKind.WEBHOOK, **kwargs)
@@ -2707,7 +2648,6 @@ class WeightedAllocationQueueSelectorAttachment(
"""Describes multiple sets of queue selectors, of which one will be selected and attached
according to a weighting.
- All required parameters must be populated in order to send to server.
:ivar allocations: A collection of percentage based weighted allocations. Required.
:vartype allocations: list[~azure.communication.jobrouter.models.QueueWeightedAllocation]
@@ -2727,17 +2667,16 @@ def __init__(
self,
*,
allocations: List["_models.QueueWeightedAllocation"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION, **kwargs)
@@ -2747,7 +2686,6 @@ class WeightedAllocationWorkerSelectorAttachment(
"""Describes multiple sets of worker selectors, of which one will be selected and attached
according to a weighting.
- All required parameters must be populated in order to send to server.
:ivar allocations: A collection of percentage based weighted allocations. Required.
:vartype allocations: list[~azure.communication.jobrouter.models.WorkerWeightedAllocation]
@@ -2767,17 +2705,16 @@ def __init__(
self,
*,
allocations: List["_models.WorkerWeightedAllocation"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, kind=WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION, **kwargs)
@@ -2785,7 +2722,6 @@ class WorkerWeightedAllocation(_model_base.Model):
"""Contains the weight percentage and worker selectors to be applied if selected for weighted
distributions.
- All required parameters must be populated in order to send to server.
:ivar weight: The percentage of this weight, expressed as a fraction of 1. Required.
:vartype weight: float
@@ -2805,15 +2741,14 @@ def __init__(
*,
weight: float,
worker_selectors: List["_models.RouterWorkerSelector"],
- ):
- ...
+ ) -> None: ...
@overload
- def __init__(self, mapping: Mapping[str, Any]):
+ def __init__(self, mapping: Mapping[str, Any]) -> None:
"""
:param mapping: raw JSON to initialize the model.
:type mapping: Mapping[str, Any]
"""
- def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py
new file mode 100644
index 000000000000..0d0dafed6a9a
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py
@@ -0,0 +1,44 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python classification_policies_create_classification_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_classification_policy(
+ classification_policy_id="90eb00c4-234e-4df7-a231-ef7895518384",
+ resource={
+ "fallbackQueueId": "MainQueue",
+ "name": "Main",
+ "prioritizationRule": {"kind": "static", "value": "2"},
+ "queueSelectorAttachments": [
+ {
+ "condition": {"expression": "1 = 1", "kind": "expression", "language": "powerFx"},
+ "kind": "conditional",
+ "queueSelectors": [{"key": "foo", "labelOperator": "equal", "value": "bar"}],
+ }
+ ],
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_CreateClassificationPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py
new file mode 100644
index 000000000000..465396004068
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python classification_policies_delete_classification_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_classification_policy(
+ classification_policy_id="MainClassificationPolicy",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_DeleteClassificationPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py
new file mode 100644
index 000000000000..da352e14e314
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python classification_policies_get_classification_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_classification_policy(
+ classification_policy_id="MainClassificationPolicy",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_GetClassificationPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py
new file mode 100644
index 000000000000..855bf8e99f00
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python classification_policies_list_classification_policies_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_classification_policies()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_ListClassificationPoliciesWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py
new file mode 100644
index 000000000000..e738587b5f46
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python classification_policies_update_classification_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_classification_policy(
+ classification_policy_id="90eb00c4-234e-4df7-a231-ef7895518384",
+ resource={"name": "MainUpdate"},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_UpdateClassificationPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py
new file mode 100644
index 000000000000..94cb32ad2e3d
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py
@@ -0,0 +1,42 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python distribution_policies_create_distribution_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_distribution_policy(
+ distribution_policy_id="d9033d56-659c-437a-b5b7-4f3b14301dd4",
+ resource={
+ "mode": {
+ "bypassSelectors": False,
+ "kind": "longestIdle",
+ "maxConcurrentOffers": 5,
+ "minConcurrentOffers": 1,
+ },
+ "name": "Main",
+ "offerExpiresAfterSeconds": 300,
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_CreateDistributionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py
new file mode 100644
index 000000000000..7abf50f632f8
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python distribution_policies_delete_distribution_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_distribution_policy(
+ distribution_policy_id="MainDistributionPolicy",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_DeleteDistributionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py
new file mode 100644
index 000000000000..23d2b5ed2f61
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python distribution_policies_get_distribution_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_distribution_policy(
+ distribution_policy_id="MainDistributionPolicy",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_GetDistributionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py
new file mode 100644
index 000000000000..b117a37dcede
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python distribution_policies_list_distribution_policies_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_distribution_policies()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_ListDistributionPoliciesWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py
new file mode 100644
index 000000000000..c32a937f6e93
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py
@@ -0,0 +1,42 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python distribution_policies_update_distribution_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_distribution_policy(
+ distribution_policy_id="d9033d56-659c-437a-b5b7-4f3b14301dd4",
+ resource={
+ "mode": {
+ "bypassSelectors": False,
+ "kind": "longestIdle",
+ "maxConcurrentOffers": 5,
+ "minConcurrentOffers": 1,
+ },
+ "name": "Main",
+ "offerExpiresAfterSeconds": 300,
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_UpdateDistributionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py
new file mode 100644
index 000000000000..41851ae7005a
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py
@@ -0,0 +1,44 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python exception_policies_create_exception_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_exception_policy(
+ exception_policy_id="cf1cda69-6f41-45ac-b252-213293f1b1cb",
+ resource={
+ "exceptionRules": [
+ {
+ "actions": [
+ {"classificationPolicyId": "Main", "kind": "reclassify", "labelsToUpsert": {"escalated": True}}
+ ],
+ "id": "MaxWaitTimeExceeded",
+ "trigger": {"kind": "waitTime", "thresholdSeconds": 20},
+ }
+ ],
+ "name": "Main",
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_CreateExceptionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py
new file mode 100644
index 000000000000..3b90010e411d
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python exception_policies_delete_exception_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_exception_policy(
+ exception_policy_id="MainExceptionPolicy",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_DeleteExceptionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py
new file mode 100644
index 000000000000..ccbde10d98bb
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python exception_policies_get_exception_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_exception_policy(
+ exception_policy_id="MainExceptionPolicy",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_GetExceptionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py
new file mode 100644
index 000000000000..8c9798ff195a
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python exception_policies_list_exception_policies_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_exception_policies()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_ListExceptionPoliciesWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py
new file mode 100644
index 000000000000..b3297bb4b718
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py
@@ -0,0 +1,44 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python exception_policies_update_exception_policy.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_exception_policy(
+ exception_policy_id="cf1cda69-6f41-45ac-b252-213293f1b1cb",
+ resource={
+ "exceptionRules": [
+ {
+ "actions": [
+ {"classificationPolicyId": "Main", "kind": "reclassify", "labelsToUpsert": {"escalated": True}}
+ ],
+ "id": "MaxWaitTimeExceeded",
+ "trigger": {"kind": "waitTime", "thresholdSeconds": 20},
+ }
+ ],
+ "name": "Main test",
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_UpdateExceptionPolicy.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py
new file mode 100644
index 000000000000..6b76a2ed3bda
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py
@@ -0,0 +1,41 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_create_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_job(
+ job_id="JobId",
+ resource={
+ "channelId": "CustomChatChannel",
+ "channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af",
+ "labels": {},
+ "matchingMode": {"kind": "queueAndMatch"},
+ "priority": 5,
+ "queueId": "MainQueue",
+ "requestedWorkerSelectors": [{"key": "Sales", "labelOperator": "equal", "value": True}],
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_CreateJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py
new file mode 100644
index 000000000000..4c2c7f5d5dce
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py
@@ -0,0 +1,41 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_create_scheduled_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_job(
+ job_id="JobId",
+ resource={
+ "channelId": "CustomChatChannel",
+ "channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af",
+ "labels": {},
+ "matchingMode": {"kind": "scheduleAndSuspend", "scheduleAt": "2023-05-26T23:22:12.0774222+00:00"},
+ "priority": 5,
+ "queueId": "MainQueue",
+ "requestedWorkerSelectors": [{"key": "Sales", "labelOperator": "equal", "value": True}],
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_CreateScheduledJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py
new file mode 100644
index 000000000000..1b3032260a08
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_delete_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_job(
+ job_id="8780b28c-7079-4de1-9143-4d369289e958",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_DeleteJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py
new file mode 100644
index 000000000000..a965ceb40016
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_get_in_queue_position.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_queue_position(
+ job_id="8780b28c-7079-4de1-9143-4d369289e958",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_GetInQueuePosition.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py
new file mode 100644
index 000000000000..fea6fb2f4a05
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_get_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_job(
+ job_id="8780b28c-7079-4de1-9143-4d369289e958",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_GetJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py
new file mode 100644
index 000000000000..153b47ac0325
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_get_jobs_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_jobs()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_GetJobsWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py
new file mode 100644
index 000000000000..d26fad4663ad
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_unassign_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.unassign_job(
+ job_id="8780b28c-7079-4de1-9143-4d369289e958",
+ assignment_id="1d5896f3-8b54-40be-82d3-910323f5e2af",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_UnassignJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py
new file mode 100644
index 000000000000..5ed758ecde34
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python jobs_update_job.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_job(
+ job_id="8780b28c-7079-4de1-9143-4d369289e958",
+ resource={"channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af"},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Jobs_UpdateJob.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py b/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py
new file mode 100644
index 000000000000..b5287855b60e
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python offers_accept_job_offer.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.accept_job_offer(
+ worker_id="DefaultWorker",
+ offer_id="1d5896f3-8b54-40be-82d3-910323f5e2af",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Offers_AcceptJobOffer.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py
new file mode 100644
index 000000000000..51402842637b
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py
@@ -0,0 +1,38 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_create_queue.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_queue(
+ queue_id="QueueId",
+ resource={
+ "distributionPolicyId": "MainDistributionPolicy",
+ "exceptionPolicyId": "MainExceptionPolicy",
+ "labels": {},
+ "name": "Main",
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_CreateQueue.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py
new file mode 100644
index 000000000000..407eef4c5da1
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_delete_queue.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_queue(
+ queue_id="MainQueue",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_DeleteQueue.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py
new file mode 100644
index 000000000000..8998904a85be
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_get_queue.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_queue(
+ queue_id="MainQueue",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_GetQueue.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py
new file mode 100644
index 000000000000..df0752a26b92
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_get_queue_statistics.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_queue_statistics(
+ queue_id="MainQueue",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_GetQueueStatistics.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py
new file mode 100644
index 000000000000..88087a0de743
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_list_queues_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_queues()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_ListQueuesWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py
new file mode 100644
index 000000000000..13ddb9543113
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python queues_update_queue.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_queue(
+ queue_id="MainQueue",
+ resource={"distributionPolicyId": "MainDistributionPolicy", "name": "Main"},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Queues_UpdateQueue.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py
new file mode 100644
index 000000000000..d7e18677d957
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py
@@ -0,0 +1,43 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_create_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={
+ "availableForOffers": False,
+ "capacity": 10,
+ "channels": [
+ {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4},
+ {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1},
+ ],
+ "labels": {},
+ "queues": ["MainQueue"],
+ "tags": {},
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_CreateWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py
new file mode 100644
index 000000000000..5dfa6f83fad1
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py
@@ -0,0 +1,44 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_create_worker_with_max_concurrent_offers.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={
+ "availableForOffers": False,
+ "capacity": 10,
+ "channels": [
+ {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4},
+ {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1},
+ ],
+ "labels": {},
+ "maxConcurrentOffers": 1,
+ "queues": ["MainQueue"],
+ "tags": {},
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_CreateWorkerWithMaxConcurrentOffers.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py
new file mode 100644
index 000000000000..3ccd7579d0c0
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_delete_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ client.delete_worker(
+ worker_id="DefaultWorker",
+ )
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_DeleteWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py
new file mode 100644
index 000000000000..0eaf2948a576
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_deregister_active_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={"availableForOffers": False, "capacity": 10},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_DeregisterActiveWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py
new file mode 100644
index 000000000000..b88bd166b574
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_deregister_inactive_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={"availableForOffers": False, "capacity": 10},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_DeregisterInactiveWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py
new file mode 100644
index 000000000000..d8aa2fc68e30
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_get_available_workers_by_channel.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_workers()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_GetAvailableWorkersByChannel.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py
new file mode 100644
index 000000000000..9afb8d995b40
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py
@@ -0,0 +1,32 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_get_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.get_worker(
+ worker_id="DefaultWorker",
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_GetWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py
new file mode 100644
index 000000000000..768d9eb4fb33
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_get_workers_with_page_size.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.list_workers()
+ for item in response:
+ print(item)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_GetWorkersWithPageSize.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py
new file mode 100644
index 000000000000..e9c6aba7218b
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py
@@ -0,0 +1,33 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_register_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={"availableForOffers": True, "capacity": 10},
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_RegisterWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py
new file mode 100644
index 000000000000..a63254a4add4
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py
@@ -0,0 +1,43 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+
+from azure.communication.jobrouter import JobRouterAdministrationClient
+
+"""
+# PREREQUISITES
+ pip install azure-communication-jobrouter
+# USAGE
+ python workers_update_worker.py
+"""
+
+
+def main():
+ client = JobRouterAdministrationClient(
+ endpoint="https://contoso.westus.communications.azure.com",
+ )
+
+ response = client.upsert_worker(
+ worker_id="WorkerId",
+ resource={
+ "availableForOffers": False,
+ "capacity": 10,
+ "channels": [
+ {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4},
+ {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1},
+ ],
+ "labels": {},
+ "queues": ["MainQueue", "SecondaryQueue"],
+ "tags": {},
+ },
+ )
+ print(response)
+
+
+# x-ms-original-file: 2024-01-18-preview/Workers_UpdateWorker.json
+if __name__ == "__main__":
+ main()
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py b/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py
new file mode 100644
index 000000000000..b3c392dc74f6
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py
@@ -0,0 +1,56 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import os
+import pytest
+from dotenv import load_dotenv
+from devtools_testutils import (
+ test_proxy,
+ add_general_regex_sanitizer,
+ add_body_key_sanitizer,
+ add_header_regex_sanitizer,
+)
+
+load_dotenv()
+
+
+# For security, please avoid record sensitive identity information in recordings
+@pytest.fixture(scope="session", autouse=True)
+def add_sanitizers(test_proxy):
+ jobrouteradministration_subscription_id = os.environ.get(
+ "JOBROUTERADMINISTRATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000"
+ )
+ jobrouteradministration_tenant_id = os.environ.get(
+ "JOBROUTERADMINISTRATION_TENANT_ID", "00000000-0000-0000-0000-000000000000"
+ )
+ jobrouteradministration_client_id = os.environ.get(
+ "JOBROUTERADMINISTRATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000"
+ )
+ jobrouteradministration_client_secret = os.environ.get(
+ "JOBROUTERADMINISTRATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000"
+ )
+ add_general_regex_sanitizer(
+ regex=jobrouteradministration_subscription_id, value="00000000-0000-0000-0000-000000000000"
+ )
+ add_general_regex_sanitizer(regex=jobrouteradministration_tenant_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=jobrouteradministration_client_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(
+ regex=jobrouteradministration_client_secret, value="00000000-0000-0000-0000-000000000000"
+ )
+
+ jobrouter_subscription_id = os.environ.get("JOBROUTER_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000")
+ jobrouter_tenant_id = os.environ.get("JOBROUTER_TENANT_ID", "00000000-0000-0000-0000-000000000000")
+ jobrouter_client_id = os.environ.get("JOBROUTER_CLIENT_ID", "00000000-0000-0000-0000-000000000000")
+ jobrouter_client_secret = os.environ.get("JOBROUTER_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=jobrouter_subscription_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=jobrouter_tenant_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=jobrouter_client_id, value="00000000-0000-0000-0000-000000000000")
+ add_general_regex_sanitizer(regex=jobrouter_client_secret, value="00000000-0000-0000-0000-000000000000")
+
+ add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]")
+ add_header_regex_sanitizer(key="Cookie", value="cookie;")
+ add_body_key_sanitizer(json_path="$..access_token", value="access_token")
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py
new file mode 100644
index 000000000000..aaa2a1f47af8
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py
@@ -0,0 +1,216 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils import recorded_by_proxy
+from testpreparer import JobRouterClientTestBase, JobRouterPreparer
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestJobRouter(JobRouterClientTestBase):
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_upsert_job(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.upsert_job(
+ job_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "assignments": {
+ "str": {
+ "assignedAt": "2020-02-20 00:00:00",
+ "assignmentId": "str",
+ "closedAt": "2020-02-20 00:00:00",
+ "completedAt": "2020-02-20 00:00:00",
+ "workerId": "str",
+ }
+ },
+ "attachedWorkerSelectors": [
+ {
+ "key": "str",
+ "labelOperator": "str",
+ "expedite": bool,
+ "expiresAfterSeconds": 0.0,
+ "expiresAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "value": {},
+ }
+ ],
+ "channelId": "str",
+ "channelReference": "str",
+ "classificationPolicyId": "str",
+ "dispositionCode": "str",
+ "enqueuedAt": "2020-02-20 00:00:00",
+ "labels": {"str": {}},
+ "matchingMode": "job_matching_mode",
+ "notes": [{"message": "str", "addedAt": "2020-02-20 00:00:00"}],
+ "priority": 0,
+ "queueId": "str",
+ "requestedWorkerSelectors": [
+ {
+ "key": "str",
+ "labelOperator": "str",
+ "expedite": bool,
+ "expiresAfterSeconds": 0.0,
+ "expiresAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "value": {},
+ }
+ ],
+ "scheduledAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "tags": {"str": {}},
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_get_job(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.get_job(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_delete_job(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.delete_job(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_list_jobs(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.list_jobs()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_get_queue_position(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.get_queue_position(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_unassign_job(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.unassign_job(
+ job_id="str",
+ assignment_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_accept_job_offer(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.accept_job_offer(
+ worker_id="str",
+ offer_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_get_queue_statistics(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.get_queue_statistics(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_upsert_worker(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.upsert_worker(
+ worker_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "assignedJobs": [
+ {"assignedAt": "2020-02-20 00:00:00", "assignmentId": "str", "capacityCost": 0, "jobId": "str"}
+ ],
+ "availableForOffers": bool,
+ "capacity": 0,
+ "channels": [{"capacityCostPerJob": 0, "channelId": "str", "maxNumberOfJobs": 0}],
+ "labels": {"str": {}},
+ "loadRatio": 0.0,
+ "maxConcurrentOffers": 0,
+ "offers": [
+ {
+ "capacityCost": 0,
+ "jobId": "str",
+ "offerId": "str",
+ "expiresAt": "2020-02-20 00:00:00",
+ "offeredAt": "2020-02-20 00:00:00",
+ }
+ ],
+ "queues": ["str"],
+ "state": "str",
+ "tags": {"str": {}},
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_get_worker(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.get_worker(
+ worker_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_delete_worker(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.delete_worker(
+ worker_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy
+ def test_list_workers(self, jobrouter_endpoint):
+ client = self.create_client(endpoint=jobrouter_endpoint)
+ response = client.list_workers()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py
new file mode 100644
index 000000000000..e90e18a13de3
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py
@@ -0,0 +1,211 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils import recorded_by_proxy
+from testpreparer import JobRouterAdministrationClientTestBase, JobRouterAdministrationPreparer
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestJobRouterAdministration(JobRouterAdministrationClientTestBase):
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_upsert_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.upsert_distribution_policy(
+ distribution_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "mode": "distribution_mode",
+ "name": "str",
+ "offerExpiresAfterSeconds": 0.0,
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_get_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.get_distribution_policy(
+ distribution_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_list_distribution_policies(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_distribution_policies()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_delete_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.delete_distribution_policy(
+ distribution_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_upsert_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.upsert_classification_policy(
+ classification_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "fallbackQueueId": "str",
+ "name": "str",
+ "prioritizationRule": "router_rule",
+ "queueSelectorAttachments": ["queue_selector_attachment"],
+ "workerSelectorAttachments": ["worker_selector_attachment"],
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_get_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.get_classification_policy(
+ classification_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_list_classification_policies(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_classification_policies()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_delete_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.delete_classification_policy(
+ classification_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_upsert_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.upsert_exception_policy(
+ exception_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "exceptionRules": [{"actions": ["exception_action"], "id": "str", "trigger": "exception_trigger"}],
+ "name": "str",
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_get_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.get_exception_policy(
+ exception_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_list_exception_policies(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_exception_policies()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_delete_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.delete_exception_policy(
+ exception_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_upsert_queue(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.upsert_queue(
+ queue_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "distributionPolicyId": "str",
+ "exceptionPolicyId": "str",
+ "labels": {"str": {}},
+ "name": "str",
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_get_queue(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.get_queue(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_list_queues(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_queues()
+ result = [r for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy
+ def test_delete_queue(self, jobrouteradministration_endpoint):
+ client = self.create_client(endpoint=jobrouteradministration_endpoint)
+ response = client.delete_queue(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py
new file mode 100644
index 000000000000..83edbf45af8a
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py
@@ -0,0 +1,212 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils.aio import recorded_by_proxy_async
+from testpreparer import JobRouterAdministrationPreparer
+from testpreparer_async import JobRouterAdministrationClientTestBaseAsync
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestJobRouterAdministrationAsync(JobRouterAdministrationClientTestBaseAsync):
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.upsert_distribution_policy(
+ distribution_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "mode": "distribution_mode",
+ "name": "str",
+ "offerExpiresAfterSeconds": 0.0,
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_get_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.get_distribution_policy(
+ distribution_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_list_distribution_policies(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_distribution_policies()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_distribution_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.delete_distribution_policy(
+ distribution_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.upsert_classification_policy(
+ classification_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "fallbackQueueId": "str",
+ "name": "str",
+ "prioritizationRule": "router_rule",
+ "queueSelectorAttachments": ["queue_selector_attachment"],
+ "workerSelectorAttachments": ["worker_selector_attachment"],
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_get_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.get_classification_policy(
+ classification_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_list_classification_policies(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_classification_policies()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_classification_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.delete_classification_policy(
+ classification_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.upsert_exception_policy(
+ exception_policy_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "exceptionRules": [{"actions": ["exception_action"], "id": "str", "trigger": "exception_trigger"}],
+ "name": "str",
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_get_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.get_exception_policy(
+ exception_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_list_exception_policies(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_exception_policies()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_exception_policy(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.delete_exception_policy(
+ exception_policy_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_queue(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.upsert_queue(
+ queue_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "distributionPolicyId": "str",
+ "exceptionPolicyId": "str",
+ "labels": {"str": {}},
+ "name": "str",
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_get_queue(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.get_queue(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_list_queues(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = client.list_queues()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterAdministrationPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_queue(self, jobrouteradministration_endpoint):
+ client = self.create_async_client(endpoint=jobrouteradministration_endpoint)
+ response = await client.delete_queue(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py
new file mode 100644
index 000000000000..f3271f5ebd47
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py
@@ -0,0 +1,217 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+import pytest
+from devtools_testutils.aio import recorded_by_proxy_async
+from testpreparer import JobRouterPreparer
+from testpreparer_async import JobRouterClientTestBaseAsync
+
+
+@pytest.mark.skip("you may need to update the auto-generated test case before run it")
+class TestJobRouterAsync(JobRouterClientTestBaseAsync):
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_job(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.upsert_job(
+ job_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "assignments": {
+ "str": {
+ "assignedAt": "2020-02-20 00:00:00",
+ "assignmentId": "str",
+ "closedAt": "2020-02-20 00:00:00",
+ "completedAt": "2020-02-20 00:00:00",
+ "workerId": "str",
+ }
+ },
+ "attachedWorkerSelectors": [
+ {
+ "key": "str",
+ "labelOperator": "str",
+ "expedite": bool,
+ "expiresAfterSeconds": 0.0,
+ "expiresAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "value": {},
+ }
+ ],
+ "channelId": "str",
+ "channelReference": "str",
+ "classificationPolicyId": "str",
+ "dispositionCode": "str",
+ "enqueuedAt": "2020-02-20 00:00:00",
+ "labels": {"str": {}},
+ "matchingMode": "job_matching_mode",
+ "notes": [{"message": "str", "addedAt": "2020-02-20 00:00:00"}],
+ "priority": 0,
+ "queueId": "str",
+ "requestedWorkerSelectors": [
+ {
+ "key": "str",
+ "labelOperator": "str",
+ "expedite": bool,
+ "expiresAfterSeconds": 0.0,
+ "expiresAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "value": {},
+ }
+ ],
+ "scheduledAt": "2020-02-20 00:00:00",
+ "status": "str",
+ "tags": {"str": {}},
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_get_job(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.get_job(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_job(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.delete_job(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_list_jobs(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = client.list_jobs()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_get_queue_position(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.get_queue_position(
+ job_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_unassign_job(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.unassign_job(
+ job_id="str",
+ assignment_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_accept_job_offer(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.accept_job_offer(
+ worker_id="str",
+ offer_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_get_queue_statistics(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.get_queue_statistics(
+ queue_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_upsert_worker(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.upsert_worker(
+ worker_id="str",
+ resource={
+ "etag": "str",
+ "id": "str",
+ "assignedJobs": [
+ {"assignedAt": "2020-02-20 00:00:00", "assignmentId": "str", "capacityCost": 0, "jobId": "str"}
+ ],
+ "availableForOffers": bool,
+ "capacity": 0,
+ "channels": [{"capacityCostPerJob": 0, "channelId": "str", "maxNumberOfJobs": 0}],
+ "labels": {"str": {}},
+ "loadRatio": 0.0,
+ "maxConcurrentOffers": 0,
+ "offers": [
+ {
+ "capacityCost": 0,
+ "jobId": "str",
+ "offerId": "str",
+ "expiresAt": "2020-02-20 00:00:00",
+ "offeredAt": "2020-02-20 00:00:00",
+ }
+ ],
+ "queues": ["str"],
+ "state": "str",
+ "tags": {"str": {}},
+ },
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_get_worker(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.get_worker(
+ worker_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_delete_worker(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = await client.delete_worker(
+ worker_id="str",
+ )
+
+ # please add some check logic here by yourself
+ # ...
+
+ @JobRouterPreparer()
+ @recorded_by_proxy_async
+ async def test_list_workers(self, jobrouter_endpoint):
+ client = self.create_async_client(endpoint=jobrouter_endpoint)
+ response = client.list_workers()
+ result = [r async for r in response]
+ # please add some check logic here by yourself
+ # ...
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py
new file mode 100644
index 000000000000..35fbaa1375aa
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py
@@ -0,0 +1,44 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+from azure.communication.jobrouter import JobRouterAdministrationClient, JobRouterClient
+from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer
+import functools
+
+
+class JobRouterAdministrationClientTestBase(AzureRecordedTestCase):
+
+ def create_client(self, endpoint):
+ credential = self.get_credential(JobRouterAdministrationClient)
+ return self.create_client_from_credential(
+ JobRouterAdministrationClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
+
+
+JobRouterAdministrationPreparer = functools.partial(
+ PowerShellPreparer,
+ "jobrouteradministration",
+ jobrouteradministration_endpoint="https://fake_jobrouteradministration_endpoint.com",
+)
+
+
+class JobRouterClientTestBase(AzureRecordedTestCase):
+
+ def create_client(self, endpoint):
+ credential = self.get_credential(JobRouterClient)
+ return self.create_client_from_credential(
+ JobRouterClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
+
+
+JobRouterPreparer = functools.partial(
+ PowerShellPreparer, "jobrouter", jobrouter_endpoint="https://fake_jobrouter_endpoint.com"
+)
diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py
new file mode 100644
index 000000000000..d84cf1c088f6
--- /dev/null
+++ b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py
@@ -0,0 +1,31 @@
+# coding=utf-8
+# --------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See License.txt in the project root for license information.
+# Code generated by Microsoft (R) Python Code Generator.
+# Changes may cause incorrect behavior and will be lost if the code is regenerated.
+# --------------------------------------------------------------------------
+from azure.communication.jobrouter.aio import JobRouterAdministrationClient, JobRouterClient
+from devtools_testutils import AzureRecordedTestCase
+
+
+class JobRouterAdministrationClientTestBaseAsync(AzureRecordedTestCase):
+
+ def create_async_client(self, endpoint):
+ credential = self.get_credential(JobRouterAdministrationClient, is_async=True)
+ return self.create_client_from_credential(
+ JobRouterAdministrationClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
+
+
+class JobRouterClientTestBaseAsync(AzureRecordedTestCase):
+
+ def create_async_client(self, endpoint):
+ credential = self.get_credential(JobRouterClient, is_async=True)
+ return self.create_client_from_credential(
+ JobRouterClient,
+ credential=credential,
+ endpoint=endpoint,
+ )
diff --git a/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py b/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py
index ee461febddf8..67e2071427d8 100644
--- a/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py
+++ b/sdk/communication/azure-communication-jobrouter/samples/router_worker_crud_ops_async.py
@@ -139,7 +139,7 @@ async def create_worker_w_limit_concurrent_offers(self):
],
labels={"Location": "NA", "English": 7, "O365": True, "Xbox_Support": False},
tags={"Name": "John Doe", "Department": "IT_HelpDesk"},
- max_concurrent_offers = 1,
+ max_concurrent_offers=1,
),
)
diff --git a/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py b/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py
index 955346bee1a6..69a0d2586209 100644
--- a/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py
+++ b/sdk/communication/azure-communication-jobrouter/tests/_shared/utils.py
@@ -20,7 +20,7 @@ def create_token_credential():
from .fake_token_credential import FakeTokenCredential
return FakeTokenCredential()
-
+
return get_credential()
@@ -32,7 +32,7 @@ def async_create_token_credential():
from .async_fake_token_credential import AsyncFakeTokenCredential
return AsyncFakeTokenCredential()
-
+
return get_credential(is_async=True)
diff --git a/sdk/communication/azure-communication-jobrouter/tests/conftest.py b/sdk/communication/azure-communication-jobrouter/tests/conftest.py
index 15c11590efd7..3eebc195c198 100644
--- a/sdk/communication/azure-communication-jobrouter/tests/conftest.py
+++ b/sdk/communication/azure-communication-jobrouter/tests/conftest.py
@@ -43,6 +43,7 @@
# fixture needs to be visible from conftest
+
# autouse=True will trigger this fixture on each pytest run, even if it's not explicitly used by a test method
@pytest.fixture(scope="session", autouse=True)
def start_proxy(test_proxy):
diff --git a/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py b/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py
index 7f4e9d46f517..a37f5abf9e9c 100644
--- a/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py
+++ b/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py
@@ -1,3 +1,4 @@
+# pylint: disable=too-many-lines
# coding: utf-8
# -------------------------------------------------------------------------
diff --git a/sdk/communication/azure-communication-jobrouter/tsp-location.yaml b/sdk/communication/azure-communication-jobrouter/tsp-location.yaml
index 81316b5b2ed6..ff468ebc2ab9 100644
--- a/sdk/communication/azure-communication-jobrouter/tsp-location.yaml
+++ b/sdk/communication/azure-communication-jobrouter/tsp-location.yaml
@@ -1,5 +1,4 @@
-repo: Azure/azure-rest-api-specs
-additionalDirectories: []
directory: specification/communication/Communication.JobRouter
-commit: 1c04f51cbfa195fe177239cf63d00d3539006800
-
+commit: 26af8eff710ea634da1b33fed369967d1c39b689
+repo: Azure/azure-rest-api-specs
+additionalDirectories: