From 7a22161812e3688b2ef5af0f661fa1c33d7ee1e0 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 16:46:26 -0400 Subject: [PATCH 1/6] switch to py3 typing --- .../messaging/webpubsubservice/_patch.py | 49 +++++++------------ 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py index 80e9e2dab37c..d2f9392da8b9 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py @@ -59,7 +59,6 @@ # pylint: disable=unused-import,ungrouped-imports from typing import Type, TypeVar, Any, Union, Dict - ClientType = TypeVar("ClientType", bound="WebPubSubServiceClient") from azure.core.credentials import TokenCredential from azure.core.pipeline import PipelineRequest @@ -80,8 +79,7 @@ def dst(self, dt): return self.__class__.ZERO -def _get_token_by_key(endpoint, hub, key, **kwargs): - # type: (str, str, str, Any) -> str +def _get_token_by_key(endpoint: str, hub: str, key: str, **kwargs: Any) -> str: """build token with access key. :param endpoint: HTTPS endpoint for the WebPubSub service instance. @@ -112,8 +110,7 @@ def _get_token_by_key(endpoint, hub, key, **kwargs): return six.ensure_str(jwt.encode(payload, key, algorithm="HS256", headers=kwargs.pop("jwt_headers", {}))) -def _parse_connection_string(connection_string, **kwargs): - # type: (str, Any) -> JSONType +def _parse_connection_string(connection_string: str, **kwargs: Any) -> JSONType: for segment in connection_string.split(";"): if "=" in segment: key, value = segment.split("=", 1) @@ -160,8 +157,7 @@ def __init__( self._original_url = origin_endpoint self._reverse_proxy_endpoint = reverse_proxy_endpoint - def on_request(self, request): - # type: (PipelineRequest) -> typing.Union[None, typing.Awaitable[None]] + def on_request(self, request: PipelineRequest) -> typing.Union[None, typing.Awaitable[None]]: """Is executed before sending the request from next policy. :param request: Request to be modified before sent from next policy. @@ -175,8 +171,7 @@ def on_request(self, request): ) return super(JwtCredentialPolicy, self).on_request(request) - def _encode(self, url): - # type: (AzureKeyCredential) -> str + def _encode(self, url: AzureKeyCredential) -> str: data = { "aud": url, "exp": datetime.now(tz=_UTC_TZ()) + timedelta(seconds=60), @@ -194,8 +189,7 @@ def _encode(self, url): class ApiManagementProxy(ProxyPolicy): - def __init__(self, **kwargs): - # type: (Any) -> None + def __init__(self, **kwargs: Any) -> None: """Create a new instance of the policy. :param endpoint: endpoint to be replaced @@ -208,8 +202,7 @@ def __init__(self, **kwargs): self._reverse_proxy_endpoint = kwargs.pop('reverse_proxy_endpoint', None) - def on_request(self, request): - # type: (PipelineRequest) -> None + def on_request(self, request: PipelineRequest) -> None: """Is executed before sending the request from next policy. :param request: Request to be modified before sent from next policy. @@ -237,13 +230,12 @@ class WebPubSubServiceClientConfiguration(Configuration): def __init__( self, - hub, # type: str - endpoint, # type: str - credential, # type: Union[TokenCredential, AzureKeyCredential] - **kwargs # type: Any - ): - # type: (...) -> None - super(WebPubSubServiceClientConfiguration, self).__init__(**kwargs) + hub: str, + endpoint: str, + credential: Union[TokenCredential, AzureKeyCredential], + **kwargs: Any + ) -> None: + super().__init__(**kwargs) api_version = kwargs.pop('api_version', "2021-10-01") # type: str if hub is None: @@ -304,12 +296,11 @@ class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): def __init__( self, - endpoint, # type: str - hub, # type: str - credential, # type: Union[TokenCredential, AzureKeyCredential] - **kwargs # type: Any - ): - # type: (...) -> None + endpoint: str, + hub: str, + credential: Union[TokenCredential, AzureKeyCredential], + **kwargs: Any + ) -> None: if kwargs.get("port") and endpoint: endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop('port')) kwargs['origin_endpoint'] = endpoint @@ -322,8 +313,7 @@ def __init__( self._serialize.client_side_validation = False @classmethod - def from_connection_string(cls, connection_string, hub, **kwargs): - # type: (Type[ClientType], str, str, Any) -> ClientType + def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) -> "WebPubSubServiceClient": """Create a new WebPubSubServiceClient from a connection string. :param connection_string: Connection string @@ -339,8 +329,7 @@ def from_connection_string(cls, connection_string, hub, **kwargs): return cls(hub=hub, credential=credential, **kwargs) @distributed_trace - def get_client_access_token(self, **kwargs): - # type: (Any) -> JSONType + def get_client_access_token(self, **kwargs: Any) -> JSONType: """Build an authentication token. :keyword user_id: User Id. From 18e66fcae5c79a33f4067f8370583dc4d20aac70 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 16:50:12 -0400 Subject: [PATCH 2/6] regen with customizations --- .../messaging/webpubsubservice/__init__.py | 14 +- .../webpubsubservice/_configuration.py | 52 +- .../webpubsubservice/_operations/__init__.py | 8 +- .../_operations/_operations.py | 1666 +++++++---------- .../webpubsubservice/_operations/_patch.py | 20 + .../messaging/webpubsubservice/_patch.py | 73 +- .../messaging/webpubsubservice/_vendor.py | 23 +- .../messaging/webpubsubservice/_version.py | 2 +- .../_web_pub_sub_service_client.py | 33 +- .../webpubsubservice/aio/__init__.py | 14 +- .../webpubsubservice/aio/_configuration.py | 49 +- .../aio/_operations/__init__.py | 8 +- .../aio/_operations/_operations.py | 852 ++++----- .../aio/_operations/_patch.py | 20 + .../messaging/webpubsubservice/aio/_patch.py | 69 +- .../messaging/webpubsubservice/aio/_vendor.py | 27 + .../aio/_web_pub_sub_service_client.py | 27 +- .../swagger/README.md | 3 +- 18 files changed, 1229 insertions(+), 1731 deletions(-) create mode 100644 sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py create mode 100644 sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py create mode 100644 sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/__init__.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/__init__.py index 656cd0b03180..daf20009e5e2 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/__init__.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/__init__.py @@ -10,10 +10,12 @@ from ._version import VERSION __version__ = VERSION -__all__ = ['WebPubSubServiceClient'] -try: - from ._patch import patch_sdk # type: ignore - patch_sdk() -except ImportError: - pass +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["WebPubSubServiceClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py index 0ad85a86eb78..591f681f4600 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_configuration.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING from azure.core.configuration import Configuration from azure.core.pipeline import policies @@ -15,37 +15,30 @@ if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any - from azure.core.credentials import TokenCredential -class WebPubSubServiceClientConfiguration(Configuration): +class WebPubSubServiceClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for WebPubSubServiceClient. Note that all parameters used to create this instance are saved as instance attributes. - :param hub: Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. + :param hub: Target hub name, which should start with alphabetic characters and only contain + alpha-numeric characters or underscore. :type hub: str :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - hub, # type: str - endpoint, # type: str - credential, # type: "TokenCredential" - **kwargs # type: Any - ): - # type: (...) -> None + def __init__(self, hub: str, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: super(WebPubSubServiceClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + api_version = kwargs.pop("api_version", "2021-10-01") # type: str if hub is None: raise ValueError("Parameter 'hub' must not be None.") @@ -58,23 +51,24 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://webpubsub.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'messaging-webpubsubservice/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/__init__.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/__init__.py index af83bc4323b2..b5ccfcd01e1b 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/__init__.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/__init__.py @@ -8,6 +8,12 @@ from ._operations import WebPubSubServiceClientOperationsMixin +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'WebPubSubServiceClientOperationsMixin', + "WebPubSubServiceClientOperationsMixin", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py index a3e45932a41a..f2393eae5b37 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,816 +6,656 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import TYPE_CHECKING -import warnings +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from msrest import Serializer + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator import distributed_trace -from msrest import Serializer -from .._vendor import _format_url_section +from .._vendor import MixinABC, _format_url_section -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Generic, IO, List, Optional, TypeVar, Union - T = TypeVar('T') - JSONType = Any - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +T = TypeVar("T") +JSONType = Any +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -# fmt: off + def build_get_client_access_token_request( - hub, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - user_id = kwargs.pop('user_id', None) # type: Optional[str] - roles = kwargs.pop('roles', None) # type: Optional[List[str]] - minutes_to_expire = kwargs.pop('minutes_to_expire', 60) # type: Optional[int] + hub: str, + *, + user_id: Optional[str] = None, + roles: Optional[List[str]] = None, + minutes_to_expire: Optional[int] = 60, + **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/:generateToken') + _url = "/api/hubs/{hub}/:generateToken" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if user_id is not None: - query_parameters['userId'] = _SERIALIZER.query("user_id", user_id, 'str') + _query_parameters["userId"] = _SERIALIZER.query("user_id", user_id, "str") if roles is not None: - query_parameters['role'] = [_SERIALIZER.query("roles", q, 'str') if q is not None else '' for q in roles] + _query_parameters["role"] = [_SERIALIZER.query("roles", q, "str") if q is not None else "" for q in roles] if minutes_to_expire is not None: - query_parameters['minutesToExpire'] = _SERIALIZER.query("minutes_to_expire", minutes_to_expire, 'int') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["minutesToExpire"] = _SERIALIZER.query("minutes_to_expire", minutes_to_expire, "int") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_close_all_connections_request( - hub, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + hub: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/:closeConnections') + _url = "/api/hubs/{hub}/:closeConnections" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if excluded is not None: - query_parameters['excluded'] = [_SERIALIZER.query("excluded", q, 'str') if q is not None else '' for q in excluded] + _query_parameters["excluded"] = [ + _SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded + ] if reason is not None: - query_parameters['reason'] = _SERIALIZER.query("reason", reason, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["reason"] = _SERIALIZER.query("reason", reason, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_send_to_all_request( - hub, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] + hub: str, *, json: JSONType = None, content: Any = None, excluded: Optional[List[str]] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + content_type = kwargs.pop("content_type", None) # type: Optional[str] accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/:send') + _url = "/api/hubs/{hub}/:send" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if excluded is not None: - query_parameters['excluded'] = [_SERIALIZER.query("excluded", q, 'str') if q is not None else '' for q in excluded] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["excluded"] = [ + _SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded + ] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest( method="POST", - url=url, - params=query_parameters, - headers=header_parameters, + url=_url, + params=_query_parameters, + headers=_header_parameters, + json=json, + content=content, **kwargs ) -def build_connection_exists_request( - hub, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_connection_exists_request(hub: str, connection_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/connections/{connectionId}') + _url = "/api/hubs/{hub}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="HEAD", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="HEAD", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_close_connection_request( - hub, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - reason = kwargs.pop('reason', None) # type: Optional[str] + hub: str, connection_id: str, *, reason: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/connections/{connectionId}') + _url = "/api/hubs/{hub}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if reason is not None: - query_parameters['reason'] = _SERIALIZER.query("reason", reason, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["reason"] = _SERIALIZER.query("reason", reason, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_send_to_connection_request( - hub, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + hub: str, connection_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + content_type = kwargs.pop("content_type", None) # type: Optional[str] accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/connections/{connectionId}/:send') + _url = "/api/hubs/{hub}/connections/{connectionId}/:send" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest( method="POST", - url=url, - params=query_parameters, - headers=header_parameters, + url=_url, + params=_query_parameters, + headers=_header_parameters, + json=json, + content=content, **kwargs ) -def build_group_exists_request( - hub, # type: str - group, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_group_exists_request(hub: str, group: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/groups/{group}') + _url = "/api/hubs/{hub}/groups/{group}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="HEAD", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="HEAD", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_close_group_connections_request( - hub, # type: str - group, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + hub: str, group: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/groups/{group}/:closeConnections') + _url = "/api/hubs/{hub}/groups/{group}/:closeConnections" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if excluded is not None: - query_parameters['excluded'] = [_SERIALIZER.query("excluded", q, 'str') if q is not None else '' for q in excluded] + _query_parameters["excluded"] = [ + _SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded + ] if reason is not None: - query_parameters['reason'] = _SERIALIZER.query("reason", reason, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["reason"] = _SERIALIZER.query("reason", reason, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_send_to_group_request( - hub, # type: str - group, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] + hub: str, + group: str, + *, + json: JSONType = None, + content: Any = None, + excluded: Optional[List[str]] = None, + **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + content_type = kwargs.pop("content_type", None) # type: Optional[str] accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/groups/{group}/:send') + _url = "/api/hubs/{hub}/groups/{group}/:send" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if excluded is not None: - query_parameters['excluded'] = [_SERIALIZER.query("excluded", q, 'str') if q is not None else '' for q in excluded] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["excluded"] = [ + _SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded + ] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest( method="POST", - url=url, - params=query_parameters, - headers=header_parameters, + url=_url, + params=_query_parameters, + headers=_header_parameters, + json=json, + content=content, **kwargs ) -def build_add_connection_to_group_request( - hub, # type: str - group, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_add_connection_to_group_request(hub: str, group: str, connection_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/groups/{group}/connections/{connectionId}') + _url = "/api/hubs/{hub}/groups/{group}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) -def build_remove_connection_from_group_request( - hub, # type: str - group, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_remove_connection_from_group_request(hub: str, group: str, connection_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/groups/{group}/connections/{connectionId}') + _url = "/api/hubs/{hub}/groups/{group}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) -def build_user_exists_request( - hub, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_user_exists_request(hub: str, user_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}') + _url = "/api/hubs/{hub}/users/{userId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="HEAD", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="HEAD", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_close_user_connections_request( - hub, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + hub: str, user_id: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}/:closeConnections') + _url = "/api/hubs/{hub}/users/{userId}/:closeConnections" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if excluded is not None: - query_parameters['excluded'] = [_SERIALIZER.query("excluded", q, 'str') if q is not None else '' for q in excluded] + _query_parameters["excluded"] = [ + _SERIALIZER.query("excluded", q, "str") if q is not None else "" for q in excluded + ] if reason is not None: - query_parameters['reason'] = _SERIALIZER.query("reason", reason, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["reason"] = _SERIALIZER.query("reason", reason, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="POST", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="POST", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_send_to_user_request( - hub, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', None) # type: Optional[str] + hub: str, user_id: str, *, json: JSONType = None, content: Any = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + content_type = kwargs.pop("content_type", None) # type: Optional[str] accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}/:send') + _url = "/api/hubs/{hub}/users/{userId}/:send" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] if content_type is not None: - header_parameters['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest( method="POST", - url=url, - params=query_parameters, - headers=header_parameters, + url=_url, + params=_query_parameters, + headers=_header_parameters, + json=json, + content=content, **kwargs ) -def build_add_user_to_group_request( - hub, # type: str - group, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_add_user_to_group_request(hub: str, group: str, user_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}/groups/{group}') + _url = "/api/hubs/{hub}/users/{userId}/groups/{group}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) -def build_remove_user_from_group_request( - hub, # type: str - group, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_remove_user_from_group_request(hub: str, group: str, user_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}/groups/{group}') + _url = "/api/hubs/{hub}/users/{userId}/groups/{group}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "group": _SERIALIZER.url("group", group, 'str', max_length=1024, min_length=1), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "group": _SERIALIZER.url("group", group, "str", max_length=1024, min_length=1), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) -def build_remove_user_from_all_groups_request( - hub, # type: str - user_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str +def build_remove_user_from_all_groups_request(hub: str, user_id: str, **kwargs: Any) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/users/{userId}/groups') + _url = "/api/hubs/{hub}/users/{userId}/groups" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "userId": _SERIALIZER.url("user_id", user_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "userId": _SERIALIZER.url("user_id", user_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_grant_permission_request( - hub, # type: str - permission, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + hub: str, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}') + _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "permission": _SERIALIZER.url("permission", permission, 'str'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "permission": _SERIALIZER.url("permission", permission, "str"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if target_name is not None: - query_parameters['targetName'] = _SERIALIZER.query("target_name", target_name, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["targetName"] = _SERIALIZER.query("target_name", target_name, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="PUT", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="PUT", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_revoke_permission_request( - hub, # type: str - permission, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + hub: str, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}') + _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "permission": _SERIALIZER.url("permission", permission, 'str'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "permission": _SERIALIZER.url("permission", permission, "str"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if target_name is not None: - query_parameters['targetName'] = _SERIALIZER.query("target_name", target_name, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["targetName"] = _SERIALIZER.query("target_name", target_name, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="DELETE", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="DELETE", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) def build_has_permission_request( - hub, # type: str - permission, # type: str - connection_id, # type: str - **kwargs # type: Any -): - # type: (...) -> HttpRequest - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + hub: str, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any +) -> HttpRequest: + api_version = kwargs.pop("api_version", "2021-10-01") # type: str accept = "application/json, text/json" # Construct URL - url = kwargs.pop("template_url", '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}') + _url = "/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}" path_format_arguments = { - "hub": _SERIALIZER.url("hub", hub, 'str', pattern=r'^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$'), - "permission": _SERIALIZER.url("permission", permission, 'str'), - "connectionId": _SERIALIZER.url("connection_id", connection_id, 'str', min_length=1), + "hub": _SERIALIZER.url("hub", hub, "str", pattern=r"^[A-Za-z][A-Za-z0-9_`,.[\]]{0,127}$"), + "permission": _SERIALIZER.url("permission", permission, "str"), + "connectionId": _SERIALIZER.url("connection_id", connection_id, "str", min_length=1), } - url = _format_url_section(url, **path_format_arguments) + _url = _format_url_section(_url, **path_format_arguments) # Construct parameters - query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] + _query_parameters = kwargs.pop("params", {}) # type: Dict[str, Any] if target_name is not None: - query_parameters['targetName'] = _SERIALIZER.query("target_name", target_name, 'str') - query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + _query_parameters["targetName"] = _SERIALIZER.query("target_name", target_name, "str") + _query_parameters["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] - header_parameters['Accept'] = _SERIALIZER.header("accept", accept, 'str') + _header_parameters = kwargs.pop("headers", {}) # type: Dict[str, Any] + _header_parameters["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest( - method="HEAD", - url=url, - params=query_parameters, - headers=header_parameters, - **kwargs - ) + return HttpRequest(method="HEAD", url=_url, params=_query_parameters, headers=_header_parameters, **kwargs) -# fmt: on -class WebPubSubServiceClientOperationsMixin(object): +class WebPubSubServiceClientOperationsMixin(MixinABC): @distributed_trace def get_client_access_token( self, - **kwargs # type: Any - ): - # type: (...) -> JSONType + *, + user_id: Optional[str] = None, + roles: Optional[List[str]] = None, + minutes_to_expire: Optional[int] = 60, + **kwargs: Any + ) -> JSONType: """Generate token for the client to connect Azure Web PubSub service. Generate token for the client to connect Azure Web PubSub service. - :keyword user_id: User Id. + :keyword user_id: User Id. Default value is None. :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. + :keyword roles: Roles that the connection with the generated token will have. Default value is + None. :paramtype roles: list[str] - :keyword minutes_to_expire: The expire time of the generated token. + :keyword minutes_to_expire: The expire time of the generated token. Default value is 60. :paramtype minutes_to_expire: int - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: JSON object :rtype: JSONType :raises: ~azure.core.exceptions.HttpResponseError @@ -824,20 +665,15 @@ def get_client_access_token( # response body for status code(s): 200 response.json() == { - "token": "str" # Optional. The token value for the WebSocket client to connect to the service. + "token": "str" # Optional. The token value for the WebSocket client to + connect to the service. } """ - cls = kwargs.pop('cls', None) # type: ClsType[JSONType] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - user_id = kwargs.pop('user_id', None) # type: Optional[str] - roles = kwargs.pop('roles', None) # type: Optional[List[str]] - minutes_to_expire = kwargs.pop('minutes_to_expire', 60) # type: Optional[int] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[JSONType] request = build_get_client_access_token_request( hub=self._config.hub, @@ -845,14 +681,15 @@ def get_client_access_token( user_id=user_id, roles=roles, minutes_to_expire=minutes_to_expire, - template_url=self.get_client_access_token.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -865,58 +702,47 @@ def get_client_access_token( deserialized = None if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get_client_access_token.metadata = {'url': '/api/hubs/{hub}/:generateToken'} # type: ignore + return cls(pipeline_response, cast(JSONType, deserialized), {}) + return cast(JSONType, deserialized) @distributed_trace - def close_all_connections( - self, - **kwargs # type: Any - ): - # type: (...) -> None + def close_all_connections( # pylint: disable=inconsistent-return-statements + self, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + ) -> None: """Close the connections in the hub. Close the connections in the hub. - :keyword excluded: Exclude these connectionIds when closing the connections in the hub. + :keyword excluded: Exclude these connectionIds when closing the connections in the hub. Default + value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_all_connections_request( hub=self._config.hub, api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_all_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -926,50 +752,44 @@ def close_all_connections( if cls: return cls(pipeline_response, None, {}) - close_all_connections.metadata = {'url': '/api/hubs/{hub}/:closeConnections'} # type: ignore - - @distributed_trace - def send_to_all( + def send_to_all( # pylint: disable=inconsistent-return-statements self, - message, # type: Union[IO, str, JSONType] - **kwargs # type: Any - ): - # type: (...) -> None + message: Union[IO, str], + *, + excluded: Optional[List[str]] = None, + content_type: Optional[str] = "application/json", + **kwargs: Any + ) -> None: """Broadcast content inside request body to all the connected client connections. Broadcast content inside request body to all the connected client connections. :param message: The payload body. - :type message: IO or str or JSONType - :keyword excluded: Excluded connection Ids. + :type message: IO or str + :keyword excluded: Excluded connection Ids. Default value is None. :paramtype excluded: list[str] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -980,17 +800,18 @@ def send_to_all( hub=self._config.hub, api_version=api_version, content_type=content_type, - json=json, - content=content, + json=_json, + content=_content, excluded=excluded, - template_url=self.send_to_all.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -1000,50 +821,37 @@ def send_to_all( if cls: return cls(pipeline_response, None, {}) - send_to_all.metadata = {'url': '/api/hubs/{hub}/:send'} # type: ignore - - @distributed_trace - def connection_exists( - self, - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> bool + def connection_exists(self, connection_id: str, **kwargs: Any) -> bool: """Check if the connection with the given connectionId exists. Check if the connection with the given connectionId exists. :param connection_id: The connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_connection_exists_request( hub=self._config.hub, connection_id=connection_id, api_version=api_version, - template_url=self.connection_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -1054,54 +862,42 @@ def connection_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - connection_exists.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}'} # type: ignore - - @distributed_trace - def close_connection( - self, - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def close_connection( # pylint: disable=inconsistent-return-statements + self, connection_id: str, *, reason: Optional[str] = None, **kwargs: Any + ) -> None: """Close the client connection. Close the client connection. :param connection_id: Target connection Id. :type connection_id: str - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - reason = kwargs.pop('reason', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_connection_request( hub=self._config.hub, connection_id=connection_id, api_version=api_version, reason=reason, - template_url=self.close_connection.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1111,17 +907,15 @@ def close_connection( if cls: return cls(pipeline_response, None, {}) - close_connection.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}'} # type: ignore - - @distributed_trace - def send_to_connection( + def send_to_connection( # pylint: disable=inconsistent-return-statements self, - connection_id, # type: str - message, # type: Union[IO, str, JSONType] - **kwargs # type: Any - ): - # type: (...) -> None + connection_id: str, + message: Union[IO, str], + *, + content_type: Optional[str] = "application/json", + **kwargs: Any + ) -> None: """Send content inside request body to the specific connection. Send content inside request body to the specific connection. @@ -1129,32 +923,28 @@ def send_to_connection( :param connection_id: The connection Id. :type connection_id: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :type message: IO or str + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -1166,16 +956,17 @@ def send_to_connection( connection_id=connection_id, api_version=api_version, content_type=content_type, - json=json, - content=content, - template_url=self.send_to_connection.metadata['url'], + json=_json, + content=_content, ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -1185,50 +976,37 @@ def send_to_connection( if cls: return cls(pipeline_response, None, {}) - send_to_connection.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}/:send'} # type: ignore - - @distributed_trace - def group_exists( - self, - group, # type: str - **kwargs # type: Any - ): - # type: (...) -> bool + def group_exists(self, group: str, **kwargs: Any) -> bool: """Check if there are any client connections inside the given group. Check if there are any client connections inside the given group. :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_group_exists_request( hub=self._config.hub, group=group, api_version=api_version, - template_url=self.group_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -1239,16 +1017,10 @@ def group_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - group_exists.metadata = {'url': '/api/hubs/{hub}/groups/{group}'} # type: ignore - - @distributed_trace - def close_group_connections( - self, - group, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def close_group_connections( # pylint: disable=inconsistent-return-statements + self, group: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + ) -> None: """Close connections in the specific group. Close connections in the specific group. @@ -1256,26 +1028,19 @@ def close_group_connections( :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str :keyword excluded: Exclude these connectionIds when closing the connections in the group. + Default value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_group_connections_request( hub=self._config.hub, @@ -1283,14 +1048,15 @@ def close_group_connections( api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_group_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1300,17 +1066,16 @@ def close_group_connections( if cls: return cls(pipeline_response, None, {}) - close_group_connections.metadata = {'url': '/api/hubs/{hub}/groups/{group}/:closeConnections'} # type: ignore - - @distributed_trace - def send_to_group( + def send_to_group( # pylint: disable=inconsistent-return-statements self, - group, # type: str - message, # type: Union[IO, str, JSONType] - **kwargs # type: Any - ): - # type: (...) -> None + group: str, + message: Union[IO, str], + *, + excluded: Optional[List[str]] = None, + content_type: Optional[str] = "application/json", + **kwargs: Any + ) -> None: """Send content inside request body to a group of connections. Send content inside request body to a group of connections. @@ -1318,35 +1083,30 @@ def send_to_group( :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword excluded: Excluded connection Ids. + :type message: IO or str + :keyword excluded: Excluded connection Ids. Default value is None. :paramtype excluded: list[str] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -1358,17 +1118,18 @@ def send_to_group( group=group, api_version=api_version, content_type=content_type, - json=json, - content=content, + json=_json, + content=_content, excluded=excluded, - template_url=self.send_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -1378,17 +1139,10 @@ def send_to_group( if cls: return cls(pipeline_response, None, {}) - send_to_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/:send'} # type: ignore - - @distributed_trace - def add_connection_to_group( - self, - group, # type: str - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def add_connection_to_group( # pylint: disable=inconsistent-return-statements + self, group: str, connection_id: str, **kwargs: Any + ) -> None: """Add a connection to the target group. Add a connection to the target group. @@ -1397,35 +1151,30 @@ def add_connection_to_group( :type group: str :param connection_id: Target connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_add_connection_to_group_request( hub=self._config.hub, group=group, connection_id=connection_id, api_version=api_version, - template_url=self.add_connection_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1435,17 +1184,10 @@ def add_connection_to_group( if cls: return cls(pipeline_response, None, {}) - add_connection_to_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/connections/{connectionId}'} # type: ignore - - @distributed_trace - def remove_connection_from_group( - self, - group, # type: str - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def remove_connection_from_group( # pylint: disable=inconsistent-return-statements + self, group: str, connection_id: str, **kwargs: Any + ) -> None: """Remove a connection from the target group. Remove a connection from the target group. @@ -1454,35 +1196,30 @@ def remove_connection_from_group( :type group: str :param connection_id: Target connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_connection_from_group_request( hub=self._config.hub, group=group, connection_id=connection_id, api_version=api_version, - template_url=self.remove_connection_from_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1492,50 +1229,37 @@ def remove_connection_from_group( if cls: return cls(pipeline_response, None, {}) - remove_connection_from_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/connections/{connectionId}'} # type: ignore - - @distributed_trace - def user_exists( - self, - user_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> bool + def user_exists(self, user_id: str, **kwargs: Any) -> bool: """Check if there are any client connections connected for the given user. Check if there are any client connections connected for the given user. :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_user_exists_request( hub=self._config.hub, user_id=user_id, api_version=api_version, - template_url=self.user_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -1546,16 +1270,10 @@ def user_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - user_exists.metadata = {'url': '/api/hubs/{hub}/users/{userId}'} # type: ignore - - @distributed_trace - def close_user_connections( - self, - user_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def close_user_connections( # pylint: disable=inconsistent-return-statements + self, user_id: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any + ) -> None: """Close connections for the specific user. Close connections for the specific user. @@ -1563,26 +1281,19 @@ def close_user_connections( :param user_id: The user Id. :type user_id: str :keyword excluded: Exclude these connectionIds when closing the connections for the user. + Default value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - excluded = kwargs.pop('excluded', None) # type: Optional[List[str]] - reason = kwargs.pop('reason', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_user_connections_request( hub=self._config.hub, @@ -1590,14 +1301,15 @@ def close_user_connections( api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_user_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1607,17 +1319,10 @@ def close_user_connections( if cls: return cls(pipeline_response, None, {}) - close_user_connections.metadata = {'url': '/api/hubs/{hub}/users/{userId}/:closeConnections'} # type: ignore - - @distributed_trace - def send_to_user( - self, - user_id, # type: str - message, # type: Union[IO, str, JSONType] - **kwargs # type: Any - ): - # type: (...) -> None + def send_to_user( # pylint: disable=inconsistent-return-statements + self, user_id: str, message: Union[IO, str], *, content_type: Optional[str] = "application/json", **kwargs: Any + ) -> None: """Send content inside request body to the specific user. Send content inside request body to the specific user. @@ -1625,32 +1330,28 @@ def send_to_user( :param user_id: The user Id. :type user_id: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :type message: IO or str + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -1662,16 +1363,17 @@ def send_to_user( user_id=user_id, api_version=api_version, content_type=content_type, - json=json, - content=content, - template_url=self.send_to_user.metadata['url'], + json=_json, + content=_content, ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -1681,17 +1383,10 @@ def send_to_user( if cls: return cls(pipeline_response, None, {}) - send_to_user.metadata = {'url': '/api/hubs/{hub}/users/{userId}/:send'} # type: ignore - - @distributed_trace - def add_user_to_group( - self, - group, # type: str - user_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def add_user_to_group( # pylint: disable=inconsistent-return-statements + self, group: str, user_id: str, **kwargs: Any + ) -> None: """Add a user to the target group. Add a user to the target group. @@ -1700,35 +1395,30 @@ def add_user_to_group( :type group: str :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_add_user_to_group_request( hub=self._config.hub, group=group, user_id=user_id, api_version=api_version, - template_url=self.add_user_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1738,17 +1428,10 @@ def add_user_to_group( if cls: return cls(pipeline_response, None, {}) - add_user_to_group.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups/{group}'} # type: ignore - - @distributed_trace - def remove_user_from_group( - self, - group, # type: str - user_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def remove_user_from_group( # pylint: disable=inconsistent-return-statements + self, group: str, user_id: str, **kwargs: Any + ) -> None: """Remove a user from the target group. Remove a user from the target group. @@ -1757,35 +1440,30 @@ def remove_user_from_group( :type group: str :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_user_from_group_request( hub=self._config.hub, group=group, user_id=user_id, api_version=api_version, - template_url=self.remove_user_from_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1795,50 +1473,39 @@ def remove_user_from_group( if cls: return cls(pipeline_response, None, {}) - remove_user_from_group.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups/{group}'} # type: ignore - - @distributed_trace - def remove_user_from_all_groups( - self, - user_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def remove_user_from_all_groups( # pylint: disable=inconsistent-return-statements + self, user_id: str, **kwargs: Any + ) -> None: """Remove a user from all groups. Remove a user from all groups. :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_user_from_all_groups_request( hub=self._config.hub, user_id=user_id, api_version=api_version, - template_url=self.remove_user_from_all_groups.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1848,17 +1515,10 @@ def remove_user_from_all_groups( if cls: return cls(pipeline_response, None, {}) - remove_user_from_all_groups.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups'} # type: ignore - - @distributed_trace - def grant_permission( - self, - permission, # type: str - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def grant_permission( # pylint: disable=inconsistent-return-statements + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any + ) -> None: """Grant permission to the connection. Grant permission to the connection. @@ -1870,23 +1530,17 @@ def grant_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_grant_permission_request( hub=self._config.hub, @@ -1894,14 +1548,15 @@ def grant_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.grant_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1911,17 +1566,10 @@ def grant_permission( if cls: return cls(pipeline_response, None, {}) - grant_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - - @distributed_trace - def revoke_permission( - self, - permission, # type: str - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> None + def revoke_permission( # pylint: disable=inconsistent-return-statements + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any + ) -> None: """Revoke permission for the connection. Revoke permission for the connection. @@ -1933,23 +1581,17 @@ def revoke_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_revoke_permission_request( hub=self._config.hub, @@ -1957,14 +1599,15 @@ def revoke_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.revoke_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1974,17 +1617,10 @@ def revoke_permission( if cls: return cls(pipeline_response, None, {}) - revoke_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - - @distributed_trace def has_permission( - self, - permission, # type: str - connection_id, # type: str - **kwargs # type: Any - ): - # type: (...) -> bool + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any + ) -> bool: """Check if a connection has permission to the specified action. Check if a connection has permission to the specified action. @@ -1996,23 +1632,17 @@ def has_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - target_name = kwargs.pop('target_name', None) # type: Optional[str] + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_has_permission_request( hub=self._config.hub, @@ -2020,14 +1650,15 @@ def has_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.has_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -2037,6 +1668,3 @@ def has_permission( if cls: return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - - has_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py index d2f9392da8b9..f0375a430e4e 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py @@ -52,14 +52,13 @@ from typing import Any, Callable, Dict, Optional, TypeVar, Union from ._operations._operations import JSONType - T = TypeVar('T') + T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Type, TypeVar, Any, Union, Dict - from azure.core.credentials import TokenCredential from azure.core.pipeline import PipelineRequest @@ -166,9 +165,7 @@ def on_request(self, request: PipelineRequest) -> typing.Union[None, typing.Awai url = request.http_request.url if self._reverse_proxy_endpoint: url = url.replace(self._reverse_proxy_endpoint, self._original_url, 1) - request.http_request.headers["Authorization"] = "Bearer " + self._encode( - url - ) + request.http_request.headers["Authorization"] = "Bearer " + self._encode(url) return super(JwtCredentialPolicy, self).on_request(request) def _encode(self, url: AzureKeyCredential) -> str: @@ -188,7 +185,6 @@ def _encode(self, url: AzureKeyCredential) -> str: class ApiManagementProxy(ProxyPolicy): - def __init__(self, **kwargs: Any) -> None: """Create a new instance of the policy. @@ -198,9 +194,8 @@ def __init__(self, **kwargs: Any) -> None: :type proxy_endpoint: str """ super(ApiManagementProxy, self).__init__(**kwargs) - self._endpoint = kwargs.pop('origin_endpoint', None) - self._reverse_proxy_endpoint = kwargs.pop('reverse_proxy_endpoint', None) - + self._endpoint = kwargs.pop("origin_endpoint", None) + self._reverse_proxy_endpoint = kwargs.pop("reverse_proxy_endpoint", None) def on_request(self, request: PipelineRequest) -> None: """Is executed before sending the request from next policy. @@ -229,14 +224,10 @@ class WebPubSubServiceClientConfiguration(Configuration): """ def __init__( - self, - hub: str, - endpoint: str, - credential: Union[TokenCredential, AzureKeyCredential], - **kwargs: Any + self, hub: str, endpoint: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs: Any ) -> None: super().__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + api_version = kwargs.pop("api_version", "2021-10-01") # type: str if hub is None: raise ValueError("Parameter 'hub' must not be None.") @@ -249,34 +240,35 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://webpubsub.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'messaging-webpubsubservice/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) self._configure(**kwargs) def _configure( - self, - **kwargs # type: Any + self, **kwargs # type: Any ): # type: (...) -> None - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or ApiManagementProxy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or ApiManagementProxy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: if isinstance(self.credential, AzureKeyCredential): self.authentication_policy = JwtCredentialPolicy( self.credential, user=kwargs.get("user"), origin_endpoint=kwargs.get("origin_endpoint"), - reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint") + reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint"), ) else: - self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): @@ -295,16 +287,12 @@ class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): """ def __init__( - self, - endpoint: str, - hub: str, - credential: Union[TokenCredential, AzureKeyCredential], - **kwargs: Any + self, endpoint: str, hub: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs: Any ) -> None: if kwargs.get("port") and endpoint: - endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop('port')) - kwargs['origin_endpoint'] = endpoint - _endpoint = '{Endpoint}' + endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop("port")) + kwargs["origin_endpoint"] = endpoint + _endpoint = "{Endpoint}" self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) @@ -353,9 +341,7 @@ def get_client_access_token(self, **kwargs: Any) -> JSONType: endpoint = self._config.endpoint.lower() if not endpoint.startswith("http://") and not endpoint.startswith("https://"): raise ValueError( - "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format( - endpoint - ) + "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) ) # Ensure endpoint has no trailing slash @@ -369,14 +355,15 @@ def get_client_access_token(self, **kwargs: Any) -> JSONType: if isinstance(self._config.credential, AzureKeyCredential): token = _get_token_by_key(endpoint, hub, self._config.credential.key, jwt_headers=jwt_headers, **kwargs) else: - token = super(WebPubSubServiceClient, self).get_client_access_token(**kwargs).get('token') + token = super(WebPubSubServiceClient, self).get_client_access_token(**kwargs).get("token") return { "baseUrl": client_url, "token": token, "url": "{}?access_token={}".format(client_url, token), } - get_client_access_token.metadata = {'url': '/api/hubs/{hub}/:generateToken'} # type: ignore + + get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py index e12b61dea670..110c2672df39 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py @@ -5,7 +5,17 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from __future__ import annotations +from abc import ABC +from typing import TYPE_CHECKING +from ._configuration import WebPubSubServiceClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from msrest import Deserializer, Serializer + + from azure.core import PipelineClient def _format_url_section(template, **kwargs): @@ -15,7 +25,14 @@ def _format_url_section(template, **kwargs): return template.format(**kwargs) except KeyError as key: formatted_components = template.split("/") - components = [ - c for c in formatted_components if "{}".format(key.args[0]) not in c - ] + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] template = "/".join(components) + + +class MixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: PipelineClient + _config: WebPubSubServiceClientConfiguration + _serialize: Serializer + _deserialize: Deserializer diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py index 961c76eb77c1..c47f66669f1b 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.1" +VERSION = "1.0.0" diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_web_pub_sub_service_client.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_web_pub_sub_service_client.py index 9d96f87e1225..d4b063feecd2 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_web_pub_sub_service_client.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_web_pub_sub_service_client.py @@ -7,20 +7,22 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import TYPE_CHECKING +from typing import Any, TYPE_CHECKING -from azure.core import PipelineClient from msrest import Deserializer, Serializer +from azure.core import PipelineClient +from azure.core.rest import HttpRequest, HttpResponse + from ._configuration import WebPubSubServiceClientConfiguration from ._operations import WebPubSubServiceClientOperationsMixin if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Dict, Optional + from typing import Dict from azure.core.credentials import TokenCredential - from azure.core.rest import HttpRequest, HttpResponse + class WebPubSubServiceClient(WebPubSubServiceClientOperationsMixin): """WebPubSubServiceClient. @@ -32,20 +34,13 @@ class WebPubSubServiceClient(WebPubSubServiceClientOperationsMixin): :type endpoint: str :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - hub, # type: str - endpoint, # type: str - credential, # type: "TokenCredential" - **kwargs # type: Any - ): - # type: (...) -> None - _endpoint = '{Endpoint}' + def __init__(self, hub: str, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{Endpoint}" self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) @@ -53,13 +48,7 @@ def __init__( self._deserialize = Deserializer() self._serialize.client_side_validation = False - - def send_request( - self, - request, # type: HttpRequest - **kwargs # type: Any - ): - # type: (...) -> HttpResponse + def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -79,7 +68,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", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/__init__.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/__init__.py index d33c98d8f4c4..cf8154564b70 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/__init__.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/__init__.py @@ -7,10 +7,12 @@ # -------------------------------------------------------------------------- from ._web_pub_sub_service_client import WebPubSubServiceClient -__all__ = ['WebPubSubServiceClient'] -try: - from ._patch import patch_sdk # type: ignore - patch_sdk() -except ImportError: - pass +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = ["WebPubSubServiceClient"] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py index 24dea080d9bd..b98b8ff20a08 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_configuration.py @@ -18,31 +18,27 @@ from azure.core.credentials_async import AsyncTokenCredential -class WebPubSubServiceClientConfiguration(Configuration): +class WebPubSubServiceClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes """Configuration for WebPubSubServiceClient. Note that all parameters used to create this instance are saved as instance attributes. - :param hub: Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. + :param hub: Target hub name, which should start with alphabetic characters and only contain + alpha-numeric characters or underscore. :type hub: str :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. :type endpoint: str :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - hub: str, - endpoint: str, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: + def __init__(self, hub: str, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: super(WebPubSubServiceClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + api_version = kwargs.pop("api_version", "2021-10-01") # type: str if hub is None: raise ValueError("Parameter 'hub' must not be None.") @@ -55,22 +51,21 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://webpubsub.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'messaging-webpubsubservice/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/__init__.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/__init__.py index af83bc4323b2..b5ccfcd01e1b 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/__init__.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/__init__.py @@ -8,6 +8,12 @@ from ._operations import WebPubSubServiceClientOperationsMixin +from ._patch import __all__ as _patch_all +from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - 'WebPubSubServiceClientOperationsMixin', + "WebPubSubServiceClientOperationsMixin", ] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py index 0fe699744e5b..6444e9c00bb7 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,23 +6,50 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import functools -from typing import Any, Callable, Dict, Generic, IO, List, Optional, TypeVar, Union -import warnings - -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error +from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, cast + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + map_error, +) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async -from ..._operations._operations import build_add_connection_to_group_request, build_add_user_to_group_request, build_close_all_connections_request, build_close_connection_request, build_close_group_connections_request, build_close_user_connections_request, build_connection_exists_request, build_get_client_access_token_request, build_grant_permission_request, build_group_exists_request, build_has_permission_request, build_remove_connection_from_group_request, build_remove_user_from_all_groups_request, build_remove_user_from_group_request, build_revoke_permission_request, build_send_to_all_request, build_send_to_connection_request, build_send_to_group_request, build_send_to_user_request, build_user_exists_request -T = TypeVar('T') +from ..._operations._operations import ( + build_add_connection_to_group_request, + build_add_user_to_group_request, + build_close_all_connections_request, + build_close_connection_request, + build_close_group_connections_request, + build_close_user_connections_request, + build_connection_exists_request, + build_get_client_access_token_request, + build_grant_permission_request, + build_group_exists_request, + build_has_permission_request, + build_remove_connection_from_group_request, + build_remove_user_from_all_groups_request, + build_remove_user_from_group_request, + build_revoke_permission_request, + build_send_to_all_request, + build_send_to_connection_request, + build_send_to_group_request, + build_send_to_user_request, + build_user_exists_request, +) +from .._vendor import MixinABC + +T = TypeVar("T") JSONType = Any ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class WebPubSubServiceClientOperationsMixin: +class WebPubSubServiceClientOperationsMixin(MixinABC): @distributed_trace_async async def get_client_access_token( self, @@ -35,15 +63,13 @@ async def get_client_access_token( Generate token for the client to connect Azure Web PubSub service. - :keyword user_id: User Id. + :keyword user_id: User Id. Default value is None. :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. + :keyword roles: Roles that the connection with the generated token will have. Default value is + None. :paramtype roles: list[str] - :keyword minutes_to_expire: The expire time of the generated token. + :keyword minutes_to_expire: The expire time of the generated token. Default value is 60. :paramtype minutes_to_expire: int - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: JSON object :rtype: JSONType :raises: ~azure.core.exceptions.HttpResponseError @@ -53,17 +79,15 @@ async def get_client_access_token( # response body for status code(s): 200 response.json() == { - "token": "str" # Optional. The token value for the WebSocket client to connect to the service. + "token": "str" # Optional. The token value for the WebSocket client to + connect to the service. } """ - cls = kwargs.pop('cls', None) # type: ClsType[JSONType] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[JSONType] request = build_get_client_access_token_request( hub=self._config.hub, @@ -71,14 +95,15 @@ async def get_client_access_token( user_id=user_id, roles=roles, minutes_to_expire=minutes_to_expire, - template_url=self.get_client_access_token.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -91,58 +116,47 @@ async def get_client_access_token( deserialized = None if cls: - return cls(pipeline_response, deserialized, {}) - - return deserialized - - get_client_access_token.metadata = {'url': '/api/hubs/{hub}/:generateToken'} # type: ignore + return cls(pipeline_response, cast(JSONType, deserialized), {}) + return cast(JSONType, deserialized) @distributed_trace_async - async def close_all_connections( - self, - *, - excluded: Optional[List[str]] = None, - reason: Optional[str] = None, - **kwargs: Any + async def close_all_connections( # pylint: disable=inconsistent-return-statements + self, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close the connections in the hub. Close the connections in the hub. - :keyword excluded: Exclude these connectionIds when closing the connections in the hub. + :keyword excluded: Exclude these connectionIds when closing the connections in the hub. Default + value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_all_connections_request( hub=self._config.hub, api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_all_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -152,15 +166,13 @@ async def close_all_connections( if cls: return cls(pipeline_response, None, {}) - close_all_connections.metadata = {'url': '/api/hubs/{hub}/:closeConnections'} # type: ignore - - @distributed_trace_async - async def send_to_all( + async def send_to_all( # pylint: disable=inconsistent-return-statements self, - message: Union[IO, str, JSONType], + message: Union[IO, str], *, excluded: Optional[List[str]] = None, + content_type: Optional[str] = "application/json", **kwargs: Any ) -> None: """Broadcast content inside request body to all the connected client connections. @@ -168,34 +180,30 @@ async def send_to_all( Broadcast content inside request body to all the connected client connections. :param message: The payload body. - :type message: IO or str or JSONType - :keyword excluded: Excluded connection Ids. + :type message: IO or str + :keyword excluded: Excluded connection Ids. Default value is None. :paramtype excluded: list[str] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -206,17 +214,18 @@ async def send_to_all( hub=self._config.hub, api_version=api_version, content_type=content_type, - json=json, - content=content, + json=_json, + content=_content, excluded=excluded, - template_url=self.send_to_all.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -226,49 +235,37 @@ async def send_to_all( if cls: return cls(pipeline_response, None, {}) - send_to_all.metadata = {'url': '/api/hubs/{hub}/:send'} # type: ignore - - @distributed_trace_async - async def connection_exists( - self, - connection_id: str, - **kwargs: Any - ) -> bool: + async def connection_exists(self, connection_id: str, **kwargs: Any) -> bool: """Check if the connection with the given connectionId exists. Check if the connection with the given connectionId exists. :param connection_id: The connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_connection_exists_request( hub=self._config.hub, connection_id=connection_id, api_version=api_version, - template_url=self.connection_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -279,16 +276,9 @@ async def connection_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - connection_exists.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async - async def close_connection( - self, - connection_id: str, - *, - reason: Optional[str] = None, - **kwargs: Any + async def close_connection( # pylint: disable=inconsistent-return-statements + self, connection_id: str, *, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close the client connection. @@ -296,37 +286,32 @@ async def close_connection( :param connection_id: Target connection Id. :type connection_id: str - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_connection_request( hub=self._config.hub, connection_id=connection_id, api_version=api_version, reason=reason, - template_url=self.close_connection.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -336,14 +321,13 @@ async def close_connection( if cls: return cls(pipeline_response, None, {}) - close_connection.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async - async def send_to_connection( + async def send_to_connection( # pylint: disable=inconsistent-return-statements self, connection_id: str, - message: Union[IO, str, JSONType], + message: Union[IO, str], + *, + content_type: Optional[str] = "application/json", **kwargs: Any ) -> None: """Send content inside request body to the specific connection. @@ -353,32 +337,28 @@ async def send_to_connection( :param connection_id: The connection Id. :type connection_id: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :type message: IO or str + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -390,16 +370,17 @@ async def send_to_connection( connection_id=connection_id, api_version=api_version, content_type=content_type, - json=json, - content=content, - template_url=self.send_to_connection.metadata['url'], + json=_json, + content=_content, ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -409,49 +390,37 @@ async def send_to_connection( if cls: return cls(pipeline_response, None, {}) - send_to_connection.metadata = {'url': '/api/hubs/{hub}/connections/{connectionId}/:send'} # type: ignore - - @distributed_trace_async - async def group_exists( - self, - group: str, - **kwargs: Any - ) -> bool: + async def group_exists(self, group: str, **kwargs: Any) -> bool: """Check if there are any client connections inside the given group. Check if there are any client connections inside the given group. :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_group_exists_request( hub=self._config.hub, group=group, api_version=api_version, - template_url=self.group_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -462,17 +431,9 @@ async def group_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - group_exists.metadata = {'url': '/api/hubs/{hub}/groups/{group}'} # type: ignore - - @distributed_trace_async - async def close_group_connections( - self, - group: str, - *, - excluded: Optional[List[str]] = None, - reason: Optional[str] = None, - **kwargs: Any + async def close_group_connections( # pylint: disable=inconsistent-return-statements + self, group: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections in the specific group. @@ -481,24 +442,19 @@ async def close_group_connections( :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str :keyword excluded: Exclude these connectionIds when closing the connections in the group. + Default value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_group_connections_request( hub=self._config.hub, @@ -506,14 +462,15 @@ async def close_group_connections( api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_group_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -523,16 +480,14 @@ async def close_group_connections( if cls: return cls(pipeline_response, None, {}) - close_group_connections.metadata = {'url': '/api/hubs/{hub}/groups/{group}/:closeConnections'} # type: ignore - - @distributed_trace_async - async def send_to_group( + async def send_to_group( # pylint: disable=inconsistent-return-statements self, group: str, - message: Union[IO, str, JSONType], + message: Union[IO, str], *, excluded: Optional[List[str]] = None, + content_type: Optional[str] = "application/json", **kwargs: Any ) -> None: """Send content inside request body to a group of connections. @@ -542,34 +497,30 @@ async def send_to_group( :param group: Target group name, which length should be greater than 0 and less than 1025. :type group: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword excluded: Excluded connection Ids. + :type message: IO or str + :keyword excluded: Excluded connection Ids. Default value is None. :paramtype excluded: list[str] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -581,17 +532,18 @@ async def send_to_group( group=group, api_version=api_version, content_type=content_type, - json=json, - content=content, + json=_json, + content=_content, excluded=excluded, - template_url=self.send_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -601,15 +553,9 @@ async def send_to_group( if cls: return cls(pipeline_response, None, {}) - send_to_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/:send'} # type: ignore - - @distributed_trace_async - async def add_connection_to_group( - self, - group: str, - connection_id: str, - **kwargs: Any + async def add_connection_to_group( # pylint: disable=inconsistent-return-statements + self, group: str, connection_id: str, **kwargs: Any ) -> None: """Add a connection to the target group. @@ -619,35 +565,30 @@ async def add_connection_to_group( :type group: str :param connection_id: Target connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_add_connection_to_group_request( hub=self._config.hub, group=group, connection_id=connection_id, api_version=api_version, - template_url=self.add_connection_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -657,15 +598,9 @@ async def add_connection_to_group( if cls: return cls(pipeline_response, None, {}) - add_connection_to_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async - async def remove_connection_from_group( - self, - group: str, - connection_id: str, - **kwargs: Any + async def remove_connection_from_group( # pylint: disable=inconsistent-return-statements + self, group: str, connection_id: str, **kwargs: Any ) -> None: """Remove a connection from the target group. @@ -675,35 +610,30 @@ async def remove_connection_from_group( :type group: str :param connection_id: Target connection Id. :type connection_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_connection_from_group_request( hub=self._config.hub, group=group, connection_id=connection_id, api_version=api_version, - template_url=self.remove_connection_from_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -713,49 +643,37 @@ async def remove_connection_from_group( if cls: return cls(pipeline_response, None, {}) - remove_connection_from_group.metadata = {'url': '/api/hubs/{hub}/groups/{group}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async - async def user_exists( - self, - user_id: str, - **kwargs: Any - ) -> bool: + async def user_exists(self, user_id: str, **kwargs: Any) -> bool: """Check if there are any client connections connected for the given user. Check if there are any client connections connected for the given user. :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_user_exists_request( hub=self._config.hub, user_id=user_id, api_version=api_version, - template_url=self.user_exists.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -766,17 +684,9 @@ async def user_exists( return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - user_exists.metadata = {'url': '/api/hubs/{hub}/users/{userId}'} # type: ignore - - @distributed_trace_async - async def close_user_connections( - self, - user_id: str, - *, - excluded: Optional[List[str]] = None, - reason: Optional[str] = None, - **kwargs: Any + async def close_user_connections( # pylint: disable=inconsistent-return-statements + self, user_id: str, *, excluded: Optional[List[str]] = None, reason: Optional[str] = None, **kwargs: Any ) -> None: """Close connections for the specific user. @@ -785,24 +695,19 @@ async def close_user_connections( :param user_id: The user Id. :type user_id: str :keyword excluded: Exclude these connectionIds when closing the connections for the user. + Default value is None. :paramtype excluded: list[str] - :keyword reason: The reason closing the client connection. + :keyword reason: The reason closing the client connection. Default value is None. :paramtype reason: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_close_user_connections_request( hub=self._config.hub, @@ -810,14 +715,15 @@ async def close_user_connections( api_version=api_version, excluded=excluded, reason=reason, - template_url=self.close_user_connections.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -827,15 +733,9 @@ async def close_user_connections( if cls: return cls(pipeline_response, None, {}) - close_user_connections.metadata = {'url': '/api/hubs/{hub}/users/{userId}/:closeConnections'} # type: ignore - - @distributed_trace_async - async def send_to_user( - self, - user_id: str, - message: Union[IO, str, JSONType], - **kwargs: Any + async def send_to_user( # pylint: disable=inconsistent-return-statements + self, user_id: str, message: Union[IO, str], *, content_type: Optional[str] = "application/json", **kwargs: Any ) -> None: """Send content inside request body to the specific user. @@ -844,32 +744,28 @@ async def send_to_user( :param user_id: The user Id. :type user_id: str :param message: The payload body. - :type message: IO or str or JSONType - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword str content_type: Media type of the body sent to the API. Default value is - "application/json". Allowed values are: "application/json", "application/octet-stream", - "text/plain." + :type message: IO or str + :keyword content_type: Media type of the body sent to the API. Possible values are: + "application/json", "application/octet-stream", and "text/plain". Default value is + "application/json". + :paramtype content_type: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str - content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] - - json = None - content = None - if content_type.split(";")[0] in ['application/json']: - json = message - elif content_type.split(";")[0] in ['application/octet-stream', 'text/plain']: - content = message + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] + + _json = None + _content = None + content_type = content_type or "" + if content_type.split(";")[0] in ["application/json"]: + _json = message + elif content_type.split(";")[0] in ["application/octet-stream", "text/plain"]: + _content = message else: raise ValueError( "The content_type '{}' is not one of the allowed values: " @@ -881,16 +777,17 @@ async def send_to_user( user_id=user_id, api_version=api_version, content_type=content_type, - json=json, - content=content, - template_url=self.send_to_user.metadata['url'], + json=_json, + content=_content, ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [202]: @@ -900,15 +797,9 @@ async def send_to_user( if cls: return cls(pipeline_response, None, {}) - send_to_user.metadata = {'url': '/api/hubs/{hub}/users/{userId}/:send'} # type: ignore - - @distributed_trace_async - async def add_user_to_group( - self, - group: str, - user_id: str, - **kwargs: Any + async def add_user_to_group( # pylint: disable=inconsistent-return-statements + self, group: str, user_id: str, **kwargs: Any ) -> None: """Add a user to the target group. @@ -918,35 +809,30 @@ async def add_user_to_group( :type group: str :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_add_user_to_group_request( hub=self._config.hub, group=group, user_id=user_id, api_version=api_version, - template_url=self.add_user_to_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -956,15 +842,9 @@ async def add_user_to_group( if cls: return cls(pipeline_response, None, {}) - add_user_to_group.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups/{group}'} # type: ignore - - @distributed_trace_async - async def remove_user_from_group( - self, - group: str, - user_id: str, - **kwargs: Any + async def remove_user_from_group( # pylint: disable=inconsistent-return-statements + self, group: str, user_id: str, **kwargs: Any ) -> None: """Remove a user from the target group. @@ -974,35 +854,30 @@ async def remove_user_from_group( :type group: str :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_user_from_group_request( hub=self._config.hub, group=group, user_id=user_id, api_version=api_version, - template_url=self.remove_user_from_group.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1012,14 +887,9 @@ async def remove_user_from_group( if cls: return cls(pipeline_response, None, {}) - remove_user_from_group.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups/{group}'} # type: ignore - - @distributed_trace_async - async def remove_user_from_all_groups( - self, - user_id: str, - **kwargs: Any + async def remove_user_from_all_groups( # pylint: disable=inconsistent-return-statements + self, user_id: str, **kwargs: Any ) -> None: """Remove a user from all groups. @@ -1027,34 +897,29 @@ async def remove_user_from_all_groups( :param user_id: Target user Id. :type user_id: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_remove_user_from_all_groups_request( hub=self._config.hub, user_id=user_id, api_version=api_version, - template_url=self.remove_user_from_all_groups.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1064,17 +929,9 @@ async def remove_user_from_all_groups( if cls: return cls(pipeline_response, None, {}) - remove_user_from_all_groups.metadata = {'url': '/api/hubs/{hub}/users/{userId}/groups'} # type: ignore - - @distributed_trace_async - async def grant_permission( - self, - permission: str, - connection_id: str, - *, - target_name: Optional[str] = None, - **kwargs: Any + async def grant_permission( # pylint: disable=inconsistent-return-statements + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any ) -> None: """Grant permission to the connection. @@ -1087,22 +944,17 @@ async def grant_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_grant_permission_request( hub=self._config.hub, @@ -1110,14 +962,15 @@ async def grant_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.grant_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200]: @@ -1127,17 +980,9 @@ async def grant_permission( if cls: return cls(pipeline_response, None, {}) - grant_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async - async def revoke_permission( - self, - permission: str, - connection_id: str, - *, - target_name: Optional[str] = None, - **kwargs: Any + async def revoke_permission( # pylint: disable=inconsistent-return-statements + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any ) -> None: """Revoke permission for the connection. @@ -1150,22 +995,17 @@ async def revoke_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: None :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_revoke_permission_request( hub=self._config.hub, @@ -1173,14 +1013,15 @@ async def revoke_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.revoke_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [204]: @@ -1190,17 +1031,9 @@ async def revoke_permission( if cls: return cls(pipeline_response, None, {}) - revoke_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - - @distributed_trace_async async def has_permission( - self, - permission: str, - connection_id: str, - *, - target_name: Optional[str] = None, - **kwargs: Any + self, permission: str, connection_id: str, *, target_name: Optional[str] = None, **kwargs: Any ) -> bool: """Check if a connection has permission to the specified action. @@ -1213,22 +1046,17 @@ async def has_permission( :type connection_id: str :keyword target_name: The meaning of the target depends on the specific permission. For joinLeaveGroup and sendToGroup, targetName is a required parameter standing for the group name. + Default value is None. :paramtype target_name: str - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str :return: bool :rtype: bool :raises: ~azure.core.exceptions.HttpResponseError """ - cls = kwargs.pop('cls', None) # type: ClsType[None] - error_map = { - 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError - } - error_map.update(kwargs.pop('error_map', {})) - - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map.update(kwargs.pop("error_map", {})) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str + cls = kwargs.pop("cls", None) # type: ClsType[None] request = build_has_permission_request( hub=self._config.hub, @@ -1236,14 +1064,15 @@ async def has_permission( connection_id=connection_id, api_version=api_version, target_name=target_name, - template_url=self.has_permission.metadata['url'], ) 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", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) + pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + request, stream=False, **kwargs + ) response = pipeline_response.http_response if response.status_code not in [200, 404]: @@ -1253,6 +1082,3 @@ async def has_permission( if cls: return cls(pipeline_response, None, {}) return 200 <= response.status_code <= 299 - - has_permission.metadata = {'url': '/api/hubs/{hub}/permissions/{permission}/connections/{connectionId}'} # type: ignore - diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py new file mode 100644 index 000000000000..f7dd32510333 --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py index 65b957b1874d..9fe4be8882e0 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py @@ -46,7 +46,7 @@ from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async -T = TypeVar('T') +T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] from ._operations._operations import JSONType @@ -71,16 +71,12 @@ class WebPubSubServiceClientConfiguration(Configuration): """ def __init__( - self, - hub: str, - endpoint: str, - credential: Union["AsyncTokenCredential", "AzureKeyCredential"], - **kwargs: Any + self, hub: str, endpoint: str, credential: Union["AsyncTokenCredential", "AzureKeyCredential"], **kwargs: Any ) -> None: super(WebPubSubServiceClientConfiguration, self).__init__(**kwargs) if kwargs.get("port") and endpoint: - endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop('port')) - api_version = kwargs.pop('api_version', "2021-10-01") # type: str + endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop("port")) + api_version = kwargs.pop("api_version", "2021-10-01") # type: str if hub is None: raise ValueError("Parameter 'hub' must not be None.") @@ -93,33 +89,32 @@ def __init__( self.endpoint = endpoint self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop('credential_scopes', ['https://webpubsub.azure.com/.default']) - kwargs.setdefault('sdk_moniker', 'messaging-webpubsubservice/{}'.format(VERSION)) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) self._configure(**kwargs) - def _configure( - self, - **kwargs: Any - ) -> None: - self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get('proxy_policy') or ApiManagementProxy(**kwargs) - self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get('authentication_policy') + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or ApiManagementProxy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") if self.credential and not self.authentication_policy: if isinstance(self.credential, AzureKeyCredential): self.authentication_policy = JwtCredentialPolicy( self.credential, user=kwargs.get("user"), origin_endpoint=kwargs.get("origin_endpoint"), - reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint") + reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint"), ) else: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs) + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): @@ -138,14 +133,10 @@ class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): """ def __init__( - self, - endpoint: str, - hub: str, - credential: Union["AsyncTokenCredential", "AzureKeyCredential"], - **kwargs: Any + self, endpoint: str, hub: str, credential: Union["AsyncTokenCredential", "AzureKeyCredential"], **kwargs: Any ) -> None: - kwargs['origin_endpoint'] = endpoint - _endpoint = '{Endpoint}' + kwargs["origin_endpoint"] = endpoint + _endpoint = "{Endpoint}" self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) @@ -209,9 +200,7 @@ async def get_client_access_token( endpoint = self._config.endpoint.lower() if not endpoint.startswith("http://") and not endpoint.startswith("https://"): raise ValueError( - "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format( - endpoint - ) + "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) ) # Ensure endpoint has no trailing slash @@ -234,19 +223,17 @@ async def get_client_access_token( ) else: access_token = await super().get_client_access_token( - user_id=user_id, - roles=roles, - minutes_to_expire=minutes_to_expire, - **kwargs + user_id=user_id, roles=roles, minutes_to_expire=minutes_to_expire, **kwargs ) - token = access_token.get('token') + token = access_token.get("token") return { "baseUrl": client_url, "token": token, "url": "{}?access_token={}".format(client_url, token), } - get_client_access_token.metadata = {'url': '/api/hubs/{hub}/:generateToken'} # type: ignore + + get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py new file mode 100644 index 000000000000..78aa190e429e --- /dev/null +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py @@ -0,0 +1,27 @@ +# -------------------------------------------------------------------------- +# 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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from __future__ import annotations +from abc import ABC +from typing import TYPE_CHECKING + +from ._configuration import WebPubSubServiceClientConfiguration + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from msrest import Deserializer, Serializer + + from azure.core import AsyncPipelineClient + + +class MixinABC(ABC): + """DO NOT use this class. It is for internal typing use only.""" + + _client: AsyncPipelineClient + _config: WebPubSubServiceClientConfiguration + _serialize: Serializer + _deserialize: Deserializer diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_web_pub_sub_service_client.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_web_pub_sub_service_client.py index 340adac20cc3..64f6f12141d8 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_web_pub_sub_service_client.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_web_pub_sub_service_client.py @@ -7,11 +7,12 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING +from typing import Any, Awaitable, TYPE_CHECKING + +from msrest import Deserializer, Serializer from azure.core import AsyncPipelineClient from azure.core.rest import AsyncHttpResponse, HttpRequest -from msrest import Deserializer, Serializer from ._configuration import WebPubSubServiceClientConfiguration from ._operations import WebPubSubServiceClientOperationsMixin @@ -22,6 +23,7 @@ from azure.core.credentials_async import AsyncTokenCredential + class WebPubSubServiceClient(WebPubSubServiceClientOperationsMixin): """WebPubSubServiceClient. @@ -32,19 +34,13 @@ class WebPubSubServiceClient(WebPubSubServiceClientOperationsMixin): :type endpoint: str :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this + :keyword api_version: Api Version. Default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - hub: str, - endpoint: str, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: - _endpoint = '{Endpoint}' + def __init__(self, hub: str, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{Endpoint}" self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) @@ -52,12 +48,7 @@ def __init__( self._deserialize = Deserializer() self._serialize.client_side_validation = False - - def send_request( - self, - request: HttpRequest, - **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: + def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -77,7 +68,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", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md b/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md index 1e36db4cab71..ae319676741d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md @@ -20,7 +20,7 @@ autorest ### Settings ```yaml -input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/main/specification/webpubsub/data-plane/WebPubSub/stable/2021-10-01/webpubsub.json +input-file: https://raw.githubusercontent.com/Azure/azure-rest-api-specs/73a0fa453a93bdbe8885f87b9e4e9fef4f0452d0/specification/webpubsub/data-plane/WebPubSub/stable/2021-10-01/webpubsub.json output-folder: ../azure/messaging/webpubsubservice namespace: azure.messaging.webpubsubservice package-name: azure-messaging-webpubsubservice @@ -34,6 +34,7 @@ head-as-boolean: true package-version: 1.0.0 add-credential: true credential-scopes: https://webpubsub.azure.com/.default +black: true ``` From bf7ceb4492414fea9b2fb218c5bf9ff10ff91567 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 17:10:13 -0400 Subject: [PATCH 3/6] pass tests --- .../webpubsubservice/_operations/_patch.py | 107 +++++++- .../messaging/webpubsubservice/_patch.py | 236 +++--------------- .../aio/_operations/_patch.py | 85 ++++++- .../messaging/webpubsubservice/aio/_patch.py | 176 +------------ 4 files changed, 229 insertions(+), 375 deletions(-) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py index f7dd32510333..e09be24b9d9d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py @@ -6,9 +6,112 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Any, List +from datetime import datetime, timedelta, tzinfo +import six +import jwt +from azure.core.credentials import AzureKeyCredential +from azure.core.tracing.decorator import distributed_trace +from ._operations import ( + WebPubSubServiceClientOperationsMixin as WebPubSubServiceClientOperationsMixinGenerated, + JSONType, +) -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + +class _UTC_TZ(tzinfo): + """from https://docs.python.org/2/library/datetime.html#tzinfo-objects""" + + ZERO = timedelta(0) + + def utcoffset(self, dt): + return self.__class__.ZERO + + def tzname(self, dt): + return "UTC" + + def dst(self, dt): + return self.__class__.ZERO + + +def get_token_by_key(endpoint: str, hub: str, key: str, **kwargs: Any) -> str: + """build token with access key. + :param endpoint: HTTPS endpoint for the WebPubSub service instance. + :type endpoint: str + :param hub: The hub to give access to. + :type hub: str + :param key: The access key + :type hub: str + :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. + :returns: token + :rtype: str + """ + audience = "{}/client/hubs/{}".format(endpoint, hub) + user = kwargs.pop("user_id", None) + ttl = timedelta(minutes=kwargs.pop("minutes_to_expire", 60)) + roles = kwargs.pop("roles", []) + + payload = { + "aud": audience, + "iat": datetime.now(tz=_UTC_TZ()), + "exp": datetime.now(tz=_UTC_TZ()) + ttl, + } + if user: + payload["sub"] = user + if roles: + payload["role"] = roles + + return six.ensure_str(jwt.encode(payload, key, algorithm="HS256", headers=kwargs.pop("jwt_headers", {}))) + + +class WebPubSubServiceClientOperationsMixin(WebPubSubServiceClientOperationsMixinGenerated): + @distributed_trace + def get_client_access_token(self, **kwargs: Any) -> JSONType: + """Build an authentication token. + :keyword user_id: User Id. + :paramtype user_id: str + :keyword roles: Roles that the connection with the generated token will have. + :paramtype roles: list[str] + :keyword minutes_to_expire: The expire time of the generated token. + :paramtype minutes_to_expire: int + :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. + :returns: JSON response containing the web socket endpoint, the token and a url with the generated access token. + :rtype: JSONType + Example: + >>> get_client_access_token() + { + 'baseUrl': 'wss://contoso.com/api/webpubsub/client/hubs/theHub', + 'token': '...', + 'url': 'wss://contoso.com/api/webpubsub/client/hubs/theHub?access_token=...' + } + """ + endpoint = self._config.endpoint.lower() + if not endpoint.startswith("http://") and not endpoint.startswith("https://"): + raise ValueError( + "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) + ) + + # Ensure endpoint has no trailing slash + endpoint = endpoint.rstrip("/") + + # Switch from http(s) to ws(s) scheme + client_endpoint = "ws" + endpoint[4:] + hub = self._config.hub + client_url = "{}/client/hubs/{}".format(client_endpoint, hub) + jwt_headers = kwargs.pop("jwt_headers", {}) + if isinstance(self._config.credential, AzureKeyCredential): + token = get_token_by_key(endpoint, hub, self._config.credential.key, jwt_headers=jwt_headers, **kwargs) + else: + token = super().get_client_access_token(**kwargs).get("token") + + return { + "baseUrl": client_url, + "token": token, + "url": "{}?access_token={}".format(client_url, token), + } + + get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore + +__all__: List[str] = ["WebPubSubServiceClientOperationsMixin"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py index f0375a430e4e..fae2104460e3 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py @@ -24,92 +24,23 @@ # IN THE SOFTWARE. # # -------------------------------------------------------------------------- -import typing +from typing import Any, TYPE_CHECKING, Optional, Union, Awaitable import jwt import six -from datetime import datetime, timedelta, tzinfo -from typing import TYPE_CHECKING -import importlib +from datetime import datetime, timedelta -from ._version import VERSION -from ._web_pub_sub_service_client import WebPubSubServiceClient as GeneratedWebPubSubServiceClient +from ._web_pub_sub_service_client import WebPubSubServiceClient as WebPubSubServiceClientGenerated +from ._operations._patch import _UTC_TZ -from msrest import Deserializer, Serializer -from azure.core.pipeline import policies -from azure.core import PipelineClient -from azure.core.configuration import Configuration +from azure.core.pipeline import PipelineRequest from azure.core.pipeline.policies import SansIOHTTPPolicy, ProxyPolicy from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator import distributed_trace -from msrest import Serializer - - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Optional, TypeVar, Union - from ._operations._operations import JSONType - - T = TypeVar("T") - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports - from typing import Type, TypeVar, Any, Union, Dict - from azure.core.credentials import TokenCredential - from azure.core.pipeline import PipelineRequest - - -class _UTC_TZ(tzinfo): - """from https://docs.python.org/2/library/datetime.html#tzinfo-objects""" - - ZERO = timedelta(0) - - def utcoffset(self, dt): - return self.__class__.ZERO - - def tzname(self, dt): - return "UTC" - - def dst(self, dt): - return self.__class__.ZERO - - -def _get_token_by_key(endpoint: str, hub: str, key: str, **kwargs: Any) -> str: - """build token with access key. - - :param endpoint: HTTPS endpoint for the WebPubSub service instance. - :type endpoint: str - :param hub: The hub to give access to. - :type hub: str - :param key: The access key - :type hub: str - :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. - :returns: token - :rtype: str - """ - audience = "{}/client/hubs/{}".format(endpoint, hub) - user = kwargs.pop("user_id", None) - ttl = timedelta(minutes=kwargs.pop("minutes_to_expire", 60)) - roles = kwargs.pop("roles", []) - payload = { - "aud": audience, - "iat": datetime.now(tz=_UTC_TZ()), - "exp": datetime.now(tz=_UTC_TZ()) + ttl, - } - if user: - payload["sub"] = user - if roles: - payload["role"] = roles - - return six.ensure_str(jwt.encode(payload, key, algorithm="HS256", headers=kwargs.pop("jwt_headers", {}))) - - -def _parse_connection_string(connection_string: str, **kwargs: Any) -> JSONType: +def _parse_connection_string(connection_string: str, **kwargs: Any) -> Any: for segment in connection_string.split(";"): if "=" in segment: key, value = segment.split("=", 1) @@ -140,9 +71,9 @@ def __init__( self, credential: AzureKeyCredential, *, - user: typing.Optional[str] = None, - origin_endpoint: typing.Optional[str] = None, - reverse_proxy_endpoint: typing.Optional[str] = None, + user: Optional[str] = None, + origin_endpoint: Optional[str] = None, + reverse_proxy_endpoint: Optional[str] = None, ) -> None: """Create a new instance of the policy associated with the given credential. @@ -156,7 +87,7 @@ def __init__( self._original_url = origin_endpoint self._reverse_proxy_endpoint = reverse_proxy_endpoint - def on_request(self, request: PipelineRequest) -> typing.Union[None, typing.Awaitable[None]]: + def on_request(self, request: PipelineRequest) -> Union[None, Awaitable[None]]: """Is executed before sending the request from next policy. :param request: Request to be modified before sent from next policy. @@ -207,71 +138,24 @@ def on_request(self, request: PipelineRequest) -> None: if self._endpoint and self._reverse_proxy_endpoint: request.http_request.url = request.http_request.url.replace(self._endpoint, self._reverse_proxy_endpoint) +class WebPubSubServiceClientBase: + """Base class for init""" -class WebPubSubServiceClientConfiguration(Configuration): - """Configuration for WebPubSubServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param hub: Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. - :type hub: str - :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. - :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. - :type credential: Union[~azure.core.credentials.TokenCredential, ~azure.core.credentials.AzureKeyCredential] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. - """ - - def __init__( - self, hub: str, endpoint: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs: Any - ) -> None: - super().__init__(**kwargs) - api_version = kwargs.pop("api_version", "2021-10-01") # type: str - - if hub is None: - raise ValueError("Parameter 'hub' must not be None.") - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.hub = hub - self.endpoint = endpoint - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or ApiManagementProxy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - if isinstance(self.credential, AzureKeyCredential): - self.authentication_policy = JwtCredentialPolicy( - self.credential, - user=kwargs.get("user"), - origin_endpoint=kwargs.get("origin_endpoint"), - reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint"), - ) - else: - self.authentication_policy = policies.BearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) - + def __init__(self, endpoint: str, hub: str, credential, **kwargs) -> None: + if kwargs.get("port") and endpoint: + endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop("port")) + kwargs["origin_endpoint"] = endpoint + if isinstance(credential, AzureKeyCredential): + kwargs["authentication_policy"] = JwtCredentialPolicy( + credential, + user=kwargs.get("user"), + origin_endpoint=kwargs.get("origin_endpoint"), + reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint") + ) + kwargs["proxy_policy"] = kwargs.pop("proxy_policy", ApiManagementProxy(**kwargs)) + super().__init__(endpoint=endpoint, hub=hub, credential=credential, **kwargs) -class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): +class WebPubSubServiceClient(WebPubSubServiceClientBase, WebPubSubServiceClientGenerated): """WebPubSubServiceClient. :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. @@ -287,18 +171,11 @@ class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): """ def __init__( - self, endpoint: str, hub: str, credential: Union[TokenCredential, AzureKeyCredential], **kwargs: Any + self, endpoint: str, hub: str, credential: Union["TokenCredential", AzureKeyCredential], **kwargs: Any ) -> None: - if kwargs.get("port") and endpoint: - endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop("port")) - kwargs["origin_endpoint"] = endpoint - _endpoint = "{Endpoint}" - self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False + super().__init__( + endpoint=endpoint, hub=hub, credential=credential, **kwargs + ) @classmethod def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) -> "WebPubSubServiceClient": @@ -316,56 +193,7 @@ def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) credential = AzureKeyCredential(kwargs.pop("accesskey")) return cls(hub=hub, credential=credential, **kwargs) - @distributed_trace - def get_client_access_token(self, **kwargs: Any) -> JSONType: - """Build an authentication token. - - :keyword user_id: User Id. - :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. - :paramtype roles: list[str] - :keyword minutes_to_expire: The expire time of the generated token. - :paramtype minutes_to_expire: int - :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. - :returns: JSON response containing the web socket endpoint, the token and a url with the generated access token. - :rtype: JSONType - - Example: - >>> get_client_access_token() - { - 'baseUrl': 'wss://contoso.com/api/webpubsub/client/hubs/theHub', - 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ...', - 'url': 'wss://contoso.com/api/webpubsub/client/hubs/theHub?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ...' - } - """ - endpoint = self._config.endpoint.lower() - if not endpoint.startswith("http://") and not endpoint.startswith("https://"): - raise ValueError( - "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) - ) - - # Ensure endpoint has no trailing slash - endpoint = endpoint.rstrip("/") - - # Switch from http(s) to ws(s) scheme - client_endpoint = "ws" + endpoint[4:] - hub = self._config.hub - client_url = "{}/client/hubs/{}".format(client_endpoint, hub) - jwt_headers = kwargs.pop("jwt_headers", {}) - if isinstance(self._config.credential, AzureKeyCredential): - token = _get_token_by_key(endpoint, hub, self._config.credential.key, jwt_headers=jwt_headers, **kwargs) - else: - token = super(WebPubSubServiceClient, self).get_client_access_token(**kwargs).get("token") - - return { - "baseUrl": client_url, - "token": token, - "url": "{}?access_token={}".format(client_url, token), - } - - get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore - +__all__ = ["WebPubSubServiceClient"] def patch_sdk(): - curr_package = importlib.import_module("azure.messaging.webpubsubservice") - curr_package.WebPubSubServiceClient = WebPubSubServiceClient + pass diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py index f7dd32510333..fae9c27cc36f 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py @@ -6,9 +6,90 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Optional, Any, Dict, List +from azure.core.credentials import AzureKeyCredential +from azure.core.tracing.decorator_async import distributed_trace_async +from ._operations import ( + WebPubSubServiceClientOperationsMixin as WebPubSubServiceClientOperationsMixinGenerated, + JSONType, +) +from ..._operations._patch import get_token_by_key -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + +class WebPubSubServiceClientOperationsMixin(WebPubSubServiceClientOperationsMixinGenerated): + @distributed_trace_async + async def get_client_access_token( # pylint: disable=arguments-differ + self, + *, + user_id: Optional[str] = None, + roles: Optional[List[str]] = None, + minutes_to_expire: Optional[int] = 60, + jwt_headers: Dict[str, Any] = None, + **kwargs: Any + ) -> JSONType: + """Generate token for the client to connect Azure Web PubSub service. + Generate token for the client to connect Azure Web PubSub service. + :keyword user_id: User Id. + :paramtype user_id: str + :keyword roles: Roles that the connection with the generated token will have. + :paramtype roles: list[str] + :keyword minutes_to_expire: The expire time of the generated token. + :paramtype minutes_to_expire: int + :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. + :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this + default value may result in unsupported behavior. + :paramtype api_version: str + :return: JSON object + :rtype: JSONType + :raises: ~azure.core.exceptions.HttpResponseError + Example: + .. code-block:: python + >>> get_client_access_token() + { + 'baseUrl': 'wss://contoso.com/api/webpubsub/client/hubs/theHub', + 'token': '...', + 'url': 'wss://contoso.com/api/webpubsub/client/hubs/theHub?access_token=...' + } + """ + endpoint = self._config.endpoint.lower() + if not endpoint.startswith("http://") and not endpoint.startswith("https://"): + raise ValueError( + "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) + ) + + # Ensure endpoint has no trailing slash + endpoint = endpoint.rstrip("/") + + # Switch from http(s) to ws(s) scheme + client_endpoint = "ws" + endpoint[4:] + hub = self._config.hub + client_url = "{}/client/hubs/{}".format(client_endpoint, hub) + if isinstance(self._config.credential, AzureKeyCredential): + token = get_token_by_key( + endpoint, + hub, + self._config.credential.key, + user_id=user_id, + roles=roles, + minutes_to_expire=minutes_to_expire, + jwt_headers=jwt_headers or {}, + **kwargs + ) + else: + access_token = await super().get_client_access_token( + user_id=user_id, roles=roles, minutes_to_expire=minutes_to_expire, **kwargs + ) + token = access_token.get("token") + + return { + "baseUrl": client_url, + "token": token, + "url": "{}?access_token={}".format(client_url, token), + } + + get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore + +__all__: List[str] = ["WebPubSubServiceClientOperationsMixin"] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py index 9fe4be8882e0..27153982a788 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py @@ -25,99 +25,23 @@ # # -------------------------------------------------------------------------- -from typing import TYPE_CHECKING -import importlib +from typing import Any, TYPE_CHECKING, Union from azure.core import AsyncPipelineClient from msrest import Deserializer -from .._version import VERSION -from .._patch import JwtCredentialPolicy, ApiManagementProxy, _parse_connection_string, _get_token_by_key -from ._web_pub_sub_service_client import WebPubSubServiceClient as GeneratedWebPubSubServiceClient +from .._patch import _parse_connection_string, WebPubSubServiceClientBase +from ._web_pub_sub_service_client import WebPubSubServiceClient as WebPubSubServiceClientGenerated -from azure.core.configuration import Configuration -from azure.core.pipeline import policies from azure.core.credentials import AzureKeyCredential from msrest import Serializer -from typing import Any, Callable, Dict, Optional, TypeVar, Union, List -from azure.core.pipeline import PipelineResponse -from azure.core.pipeline.transport import AsyncHttpResponse -from azure.core.rest import HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -from ._operations._operations import JSONType if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class WebPubSubServiceClientConfiguration(Configuration): - """Configuration for WebPubSubServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param hub: Target hub name, which should start with alphabetic characters and only contain alpha-numeric characters or underscore. - :type hub: str - :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. - :type endpoint: str - :param credential: Credential needed for the client to connect to Azure. - :type credential: Union[~azure.core.credentials_async.AsyncTokenCredential, ~azure.core.credentials.AzureKeyCredential] - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, hub: str, endpoint: str, credential: Union["AsyncTokenCredential", "AzureKeyCredential"], **kwargs: Any - ) -> None: - super(WebPubSubServiceClientConfiguration, self).__init__(**kwargs) - if kwargs.get("port") and endpoint: - endpoint = endpoint.rstrip("/") + ":{}".format(kwargs.pop("port")) - api_version = kwargs.pop("api_version", "2021-10-01") # type: str - - if hub is None: - raise ValueError("Parameter 'hub' must not be None.") - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.hub = hub - self.endpoint = endpoint - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://webpubsub.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "messaging-webpubsubservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or ApiManagementProxy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - if isinstance(self.credential, AzureKeyCredential): - self.authentication_policy = JwtCredentialPolicy( - self.credential, - user=kwargs.get("user"), - origin_endpoint=kwargs.get("origin_endpoint"), - reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint"), - ) - else: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) - - -class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): +class WebPubSubServiceClient(WebPubSubServiceClientBase, WebPubSubServiceClientGenerated): """WebPubSubServiceClient. :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. @@ -133,20 +57,14 @@ class WebPubSubServiceClient(GeneratedWebPubSubServiceClient): """ def __init__( - self, endpoint: str, hub: str, credential: Union["AsyncTokenCredential", "AzureKeyCredential"], **kwargs: Any + self, endpoint: str, hub: str, credential: Union["AsyncTokenCredential", AzureKeyCredential], **kwargs: Any ) -> None: - kwargs["origin_endpoint"] = endpoint - _endpoint = "{Endpoint}" - self._config = WebPubSubServiceClientConfiguration(hub=hub, endpoint=endpoint, credential=credential, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False + super().__init__(endpoint=endpoint, hub=hub, credential=credential, **kwargs) @classmethod def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) -> "WebPubSubServiceClient": """Create a new WebPubSubServiceClient from a connection string. + :param connection_string: Connection string :type connection_string: ~str :param hub: Target hub name, which should start with alphabetic characters and only contain @@ -159,83 +77,7 @@ def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) credential = AzureKeyCredential(kwargs.pop("accesskey")) return cls(hub=hub, credential=credential, **kwargs) - @distributed_trace_async - async def get_client_access_token( - self, - *, - user_id: Optional[str] = None, - roles: Optional[List[str]] = None, - minutes_to_expire: Optional[int] = 60, - jwt_headers: Dict[str, Any] = None, - **kwargs: Any - ) -> JSONType: - """Generate token for the client to connect Azure Web PubSub service. - - Generate token for the client to connect Azure Web PubSub service. - - :keyword user_id: User Id. - :paramtype user_id: str - :keyword roles: Roles that the connection with the generated token will have. - :paramtype roles: list[str] - :keyword minutes_to_expire: The expire time of the generated token. - :paramtype minutes_to_expire: int - :keyword dict[str, any] jwt_headers: Any headers you want to pass to jwt encoding. - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :return: JSON object - :rtype: JSONType - :raises: ~azure.core.exceptions.HttpResponseError - - Example: - .. code-block:: python - - >>> get_client_access_token() - { - 'baseUrl': 'wss://contoso.com/api/webpubsub/client/hubs/theHub', - 'token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ...', - 'url': 'wss://contoso.com/api/webpubsub/client/hubs/theHub?access_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ...' - } - """ - endpoint = self._config.endpoint.lower() - if not endpoint.startswith("http://") and not endpoint.startswith("https://"): - raise ValueError( - "Invalid endpoint: '{}' has unknown scheme - expected 'http://' or 'https://'".format(endpoint) - ) - - # Ensure endpoint has no trailing slash - endpoint = endpoint.rstrip("/") - - # Switch from http(s) to ws(s) scheme - client_endpoint = "ws" + endpoint[4:] - hub = self._config.hub - client_url = "{}/client/hubs/{}".format(client_endpoint, hub) - if isinstance(self._config.credential, AzureKeyCredential): - token = _get_token_by_key( - endpoint, - hub, - self._config.credential.key, - user_id=user_id, - roles=roles, - minutes_to_expire=minutes_to_expire, - jwt_headers=jwt_headers or {}, - **kwargs - ) - else: - access_token = await super().get_client_access_token( - user_id=user_id, roles=roles, minutes_to_expire=minutes_to_expire, **kwargs - ) - token = access_token.get("token") - - return { - "baseUrl": client_url, - "token": token, - "url": "{}?access_token={}".format(client_url, token), - } - - get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore - +__all__ = ["WebPubSubServiceClient"] def patch_sdk(): - curr_package = importlib.import_module("azure.messaging.webpubsubservice.aio") - curr_package.WebPubSubServiceClient = WebPubSubServiceClient + pass From 93ed559e60813411622670a650a9573ee68d235d Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 17:14:31 -0400 Subject: [PATCH 4/6] lint --- eng/tox/allowed_pylint_failures.py | 1 - .../webpubsubservice/_operations/_patch.py | 5 ++++- .../messaging/webpubsubservice/_patch.py | 20 +++++++++++-------- .../aio/_operations/_patch.py | 5 ++++- .../messaging/webpubsubservice/aio/_patch.py | 11 ++++------ 5 files changed, 24 insertions(+), 18 deletions(-) diff --git a/eng/tox/allowed_pylint_failures.py b/eng/tox/allowed_pylint_failures.py index b8c99576e6f9..a2421870ded3 100644 --- a/eng/tox/allowed_pylint_failures.py +++ b/eng/tox/allowed_pylint_failures.py @@ -55,7 +55,6 @@ "azure-purview-scanning", "azure-purview-catalog", "azure-purview-account", - "azure-messaging-webpubsubservice", "azure-purview-administration", "azure-messaging-nspkg", "azure-agrifood-farming", diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py index e09be24b9d9d..8dfdb570225d 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_operations/_patch.py @@ -111,7 +111,10 @@ def get_client_access_token(self, **kwargs: Any) -> JSONType: get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore -__all__: List[str] = ["WebPubSubServiceClientOperationsMixin"] # Add all objects you want publicly available to users at this package level + +__all__: List[str] = [ + "WebPubSubServiceClientOperationsMixin" +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py index fae2104460e3..7a38e871615e 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_patch.py @@ -25,21 +25,23 @@ # # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING, Optional, Union, Awaitable +from datetime import datetime, timedelta import jwt import six -from datetime import datetime, timedelta - -from ._web_pub_sub_service_client import WebPubSubServiceClient as WebPubSubServiceClientGenerated -from ._operations._patch import _UTC_TZ from azure.core.pipeline import PipelineRequest from azure.core.pipeline.policies import SansIOHTTPPolicy, ProxyPolicy from azure.core.credentials import AzureKeyCredential +from ._web_pub_sub_service_client import WebPubSubServiceClient as WebPubSubServiceClientGenerated +from ._operations._patch import _UTC_TZ + + if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials import TokenCredential + def _parse_connection_string(connection_string: str, **kwargs: Any) -> Any: for segment in connection_string.split(";"): if "=" in segment: @@ -138,6 +140,7 @@ def on_request(self, request: PipelineRequest) -> None: if self._endpoint and self._reverse_proxy_endpoint: request.http_request.url = request.http_request.url.replace(self._endpoint, self._reverse_proxy_endpoint) + class WebPubSubServiceClientBase: """Base class for init""" @@ -150,11 +153,12 @@ def __init__(self, endpoint: str, hub: str, credential, **kwargs) -> None: credential, user=kwargs.get("user"), origin_endpoint=kwargs.get("origin_endpoint"), - reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint") + reverse_proxy_endpoint=kwargs.get("reverse_proxy_endpoint"), ) kwargs["proxy_policy"] = kwargs.pop("proxy_policy", ApiManagementProxy(**kwargs)) super().__init__(endpoint=endpoint, hub=hub, credential=credential, **kwargs) + class WebPubSubServiceClient(WebPubSubServiceClientBase, WebPubSubServiceClientGenerated): """WebPubSubServiceClient. @@ -173,9 +177,7 @@ class WebPubSubServiceClient(WebPubSubServiceClientBase, WebPubSubServiceClientG def __init__( self, endpoint: str, hub: str, credential: Union["TokenCredential", AzureKeyCredential], **kwargs: Any ) -> None: - super().__init__( - endpoint=endpoint, hub=hub, credential=credential, **kwargs - ) + super().__init__(endpoint=endpoint, hub=hub, credential=credential, **kwargs) @classmethod def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) -> "WebPubSubServiceClient": @@ -193,7 +195,9 @@ def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) credential = AzureKeyCredential(kwargs.pop("accesskey")) return cls(hub=hub, credential=credential, **kwargs) + __all__ = ["WebPubSubServiceClient"] + def patch_sdk(): pass diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py index fae9c27cc36f..192dd6142745 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_operations/_patch.py @@ -89,7 +89,10 @@ async def get_client_access_token( # pylint: disable=arguments-differ get_client_access_token.metadata = {"url": "/api/hubs/{hub}/:generateToken"} # type: ignore -__all__: List[str] = ["WebPubSubServiceClientOperationsMixin"] # Add all objects you want publicly available to users at this package level + +__all__: List[str] = [ + "WebPubSubServiceClientOperationsMixin" +] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py index 27153982a788..4da808aacffc 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_patch.py @@ -24,18 +24,13 @@ # IN THE SOFTWARE. # # -------------------------------------------------------------------------- - from typing import Any, TYPE_CHECKING, Union -from azure.core import AsyncPipelineClient -from msrest import Deserializer +from azure.core.credentials import AzureKeyCredential -from .._patch import _parse_connection_string, WebPubSubServiceClientBase +from .._patch import _parse_connection_string, WebPubSubServiceClientBase from ._web_pub_sub_service_client import WebPubSubServiceClient as WebPubSubServiceClientGenerated -from azure.core.credentials import AzureKeyCredential -from msrest import Serializer - if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -77,7 +72,9 @@ def from_connection_string(cls, connection_string: str, hub: str, **kwargs: Any) credential = AzureKeyCredential(kwargs.pop("accesskey")) return cls(hub=hub, credential=credential, **kwargs) + __all__ = ["WebPubSubServiceClient"] + def patch_sdk(): pass From 1b4448c9c45d0fe77208e5ef579c3ddb15f08fbf Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 17:54:23 -0400 Subject: [PATCH 5/6] make 3.6 compatible --- .../azure/messaging/webpubsubservice/_vendor.py | 7 +++---- .../azure/messaging/webpubsubservice/aio/_vendor.py | 7 +++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py index 110c2672df39..8ae35c098af5 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_vendor.py @@ -5,7 +5,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from __future__ import annotations from abc import ABC from typing import TYPE_CHECKING @@ -32,7 +31,7 @@ def _format_url_section(template, **kwargs): class MixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" - _client: PipelineClient + _client: "PipelineClient" _config: WebPubSubServiceClientConfiguration - _serialize: Serializer - _deserialize: Deserializer + _serialize: "Serializer" + _deserialize: "Deserializer" diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py index 78aa190e429e..680ae3da4def 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/aio/_vendor.py @@ -5,7 +5,6 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from __future__ import annotations from abc import ABC from typing import TYPE_CHECKING @@ -21,7 +20,7 @@ class MixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" - _client: AsyncPipelineClient + _client: "AsyncPipelineClient" _config: WebPubSubServiceClientConfiguration - _serialize: Serializer - _deserialize: Deserializer + _serialize: "Serializer" + _deserialize: "Deserializer" From 7bdf2925d04e55505d394d9adc3ffcf67cabc75f Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Mon, 14 Mar 2022 18:23:30 -0400 Subject: [PATCH 6/6] fix package version --- .../azure/messaging/webpubsubservice/_version.py | 2 +- .../azure-messaging-webpubsubservice/swagger/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py index c47f66669f1b..961c76eb77c1 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/azure/messaging/webpubsubservice/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0" +VERSION = "1.0.1" diff --git a/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md b/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md index ae319676741d..a6d333074686 100644 --- a/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md +++ b/sdk/webpubsub/azure-messaging-webpubsubservice/swagger/README.md @@ -31,7 +31,7 @@ python: true title: WebPubSubServiceClient version-tolerant: true head-as-boolean: true -package-version: 1.0.0 +package-version: 1.0.1 add-credential: true credential-scopes: https://webpubsub.azure.com/.default black: true