Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/__init__.py +37 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/_version.py +7 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/client_factory.py +295 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/cloud.py +30 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/credentials.py +171 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/exceptions.py +22 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/__init__.py +41 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_enum_meta.py +66 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_match_conditions.py +46 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_pipeline_client.py +201 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_pipeline_client_async.py +289 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_version.py +12 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/async_paging.py +151 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/configuration.py +148 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/credentials.py +175 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/credentials_async.py +48 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/exceptions.py +582 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/messaging.py +229 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/paging.py +125 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/py.typed +0 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/serialization.py +125 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/settings.py +490 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/__init__.py +64 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_auth_record.py +114 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_bearer_token_provider.py +46 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_constants.py +55 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_enums.py +67 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_exceptions.py +50 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_persistent_cache.py +116 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_version.py +5 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/py.typed +0 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/__init__.py +33 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_async_pipeline_client.py +66 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_pipeline_client.py +61 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_version.py +12 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/exceptions.py +81 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/py.typed +0 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/tools.py +209 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/__init__.py +1 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/_version.py +8 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/__init__.py +24 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/_version.py +8 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/__init__.py +20 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_changes_client.py +115 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_configuration.py +67 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_serialization.py +1998 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_version.py +8 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/models.py +7 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/__init__.py +20 -0
- pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/_configuration.py +67 -0
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
from ._version import VERSION as _VERSION
|
| 7 |
+
|
| 8 |
+
__author__ = 'Microsoft Corp. <azpysdkhelp@microsoft.com>'
|
| 9 |
+
__version__ = _VERSION
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class AzureException(Exception):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AzureHttpError(AzureException):
|
| 17 |
+
def __init__(self, message, status_code):
|
| 18 |
+
super(AzureHttpError, self).__init__(message)
|
| 19 |
+
self.status_code = status_code
|
| 20 |
+
|
| 21 |
+
def __new__(cls, message, status_code, *args, **kwargs):
|
| 22 |
+
if cls is AzureHttpError:
|
| 23 |
+
if status_code == 404:
|
| 24 |
+
cls = AzureMissingResourceHttpError
|
| 25 |
+
elif status_code == 409:
|
| 26 |
+
cls = AzureConflictHttpError
|
| 27 |
+
return AzureException.__new__(cls, message, status_code, *args, **kwargs)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AzureConflictHttpError(AzureHttpError):
|
| 31 |
+
def __init__(self, message, status_code):
|
| 32 |
+
super(AzureConflictHttpError, self).__init__(message, status_code)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class AzureMissingResourceHttpError(AzureHttpError):
|
| 36 |
+
def __init__(self, message, status_code):
|
| 37 |
+
super(AzureMissingResourceHttpError, self).__init__(message, status_code)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/_version.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
VERSION = "1.1.28"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/client_factory.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
import io
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
import warnings
|
| 13 |
+
try:
|
| 14 |
+
from inspect import getfullargspec as get_arg_spec
|
| 15 |
+
except ImportError:
|
| 16 |
+
from inspect import getargspec as get_arg_spec
|
| 17 |
+
|
| 18 |
+
from .credentials import get_azure_cli_credentials
|
| 19 |
+
from .cloud import get_cli_active_cloud
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _instantiate_client(client_class, **kwargs):
|
| 23 |
+
"""Instantiate a client from kwargs, filtering kwargs to match client signature.
|
| 24 |
+
"""
|
| 25 |
+
args = get_arg_spec(client_class.__init__).args
|
| 26 |
+
for key in ['subscription_id', 'tenant_id', 'base_url', 'credential', 'credentials']:
|
| 27 |
+
if key not in kwargs:
|
| 28 |
+
continue
|
| 29 |
+
if key not in args:
|
| 30 |
+
del kwargs[key]
|
| 31 |
+
elif sys.version_info < (3, 0) and isinstance(kwargs[key], unicode):
|
| 32 |
+
kwargs[key] = kwargs[key].encode('utf-8')
|
| 33 |
+
return client_class(**kwargs)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _client_resource(client_class, cloud):
|
| 37 |
+
"""Return a tuple of the resource (used to get the right access token), and the base URL for the client.
|
| 38 |
+
Either or both can be None to signify that the default value should be used.
|
| 39 |
+
"""
|
| 40 |
+
if client_class.__name__ == 'GraphRbacManagementClient':
|
| 41 |
+
return cloud.endpoints.active_directory_graph_resource_id, cloud.endpoints.active_directory_graph_resource_id
|
| 42 |
+
if client_class.__name__ == 'ApplicationInsightsDataClient':
|
| 43 |
+
return cloud.endpoints.app_insights_resource_id, cloud.endpoints.app_insights_resource_id+"/v1"
|
| 44 |
+
if client_class.__name__ == 'KeyVaultClient':
|
| 45 |
+
vault_host = cloud.suffixes.keyvault_dns[1:]
|
| 46 |
+
vault_url = 'https://{}'.format(vault_host)
|
| 47 |
+
return vault_url, None
|
| 48 |
+
return None, None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_client_from_cli_profile(client_class, **kwargs):
|
| 52 |
+
"""Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
|
| 53 |
+
|
| 54 |
+
*Disclaimer*: This is NOT the recommended approach to authenticate with CLI login, this method is deprecated.
|
| 55 |
+
use https://pypi.org/project/azure-identity/ and AzureCliCredential instead. See example code below:
|
| 56 |
+
|
| 57 |
+
.. code:: python
|
| 58 |
+
|
| 59 |
+
from azure.identity import AzureCliCredential
|
| 60 |
+
from azure.mgmt.compute import ComputeManagementClient
|
| 61 |
+
client = ComputeManagementClient(AzureCliCredential(), subscription_id)
|
| 62 |
+
|
| 63 |
+
This method is not working for azure-cli-core>=2.21.0 (released in March 2021).
|
| 64 |
+
|
| 65 |
+
For compatible azure-cli-core (< 2.20.0), This method will automatically fill the following client parameters:
|
| 66 |
+
- credentials/credential
|
| 67 |
+
- subscription_id
|
| 68 |
+
- base_url
|
| 69 |
+
|
| 70 |
+
Parameters provided in kwargs will override CLI parameters and be passed directly to the client.
|
| 71 |
+
|
| 72 |
+
:Example:
|
| 73 |
+
|
| 74 |
+
.. code:: python
|
| 75 |
+
|
| 76 |
+
from azure.common.client_factory import get_client_from_cli_profile
|
| 77 |
+
from azure.mgmt.compute import ComputeManagementClient
|
| 78 |
+
client = get_client_from_cli_profile(ComputeManagementClient)
|
| 79 |
+
|
| 80 |
+
.. versionadded:: 1.1.6
|
| 81 |
+
|
| 82 |
+
.. deprecated:: 1.1.28
|
| 83 |
+
|
| 84 |
+
.. seealso:: https://aka.ms/azsdk/python/identity/migration
|
| 85 |
+
|
| 86 |
+
:param client_class: A SDK client class
|
| 87 |
+
:return: An instantiated client
|
| 88 |
+
:raises: ImportError if azure-cli-core package is not available
|
| 89 |
+
"""
|
| 90 |
+
warnings.warn(
|
| 91 |
+
"get_client_from_cli_profile is deprecated, please use azure-identity and AzureCliCredential instead. "+
|
| 92 |
+
"See also https://aka.ms/azsdk/python/identity/migration.",
|
| 93 |
+
DeprecationWarning
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
cloud = get_cli_active_cloud()
|
| 97 |
+
parameters = {}
|
| 98 |
+
no_credential_sentinel = object()
|
| 99 |
+
kwarg_cred = kwargs.pop('credentials', no_credential_sentinel)
|
| 100 |
+
if kwarg_cred is no_credential_sentinel:
|
| 101 |
+
kwarg_cred = kwargs.pop('credential', no_credential_sentinel)
|
| 102 |
+
|
| 103 |
+
if kwarg_cred is no_credential_sentinel or 'subscription_id' not in kwargs:
|
| 104 |
+
resource, _ = _client_resource(client_class, cloud)
|
| 105 |
+
credentials, subscription_id, tenant_id = get_azure_cli_credentials(
|
| 106 |
+
resource=resource,
|
| 107 |
+
with_tenant=True,
|
| 108 |
+
)
|
| 109 |
+
# Provide both syntax of cred, we have an "inspect" filter later
|
| 110 |
+
credential_to_pass = credentials if kwarg_cred is no_credential_sentinel else kwarg_cred
|
| 111 |
+
parameters.update({
|
| 112 |
+
'credentials': credential_to_pass,
|
| 113 |
+
'credential': credential_to_pass,
|
| 114 |
+
'subscription_id': kwargs.get('subscription_id', subscription_id)
|
| 115 |
+
})
|
| 116 |
+
|
| 117 |
+
args = get_arg_spec(client_class.__init__).args
|
| 118 |
+
if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs: # Datalake
|
| 119 |
+
# Let it raise here with AttributeError at worst, this would mean this cloud does not define
|
| 120 |
+
# ADL endpoint and no manual suffix was given
|
| 121 |
+
parameters['adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
|
| 122 |
+
elif 'base_url' in args and 'base_url' not in kwargs:
|
| 123 |
+
_, base_url = _client_resource(client_class, cloud)
|
| 124 |
+
if base_url:
|
| 125 |
+
parameters['base_url'] = base_url
|
| 126 |
+
else:
|
| 127 |
+
parameters['base_url'] = cloud.endpoints.resource_manager
|
| 128 |
+
if 'tenant_id' in args and 'tenant_id' not in kwargs:
|
| 129 |
+
parameters['tenant_id'] = tenant_id
|
| 130 |
+
parameters.update(kwargs)
|
| 131 |
+
return _instantiate_client(client_class, **parameters)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _is_autorest_v3(client_class):
|
| 135 |
+
"""Is this client a autorestv3/track2 one?.
|
| 136 |
+
Could be refined later if necessary.
|
| 137 |
+
"""
|
| 138 |
+
args = get_arg_spec(client_class.__init__).args
|
| 139 |
+
return "credential" in args
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def get_client_from_json_dict(client_class, config_dict, **kwargs):
|
| 143 |
+
"""Return a SDK client initialized with a JSON auth dict.
|
| 144 |
+
|
| 145 |
+
*Disclaimer*: This is NOT the recommended approach, see https://aka.ms/azsdk/python/identity/migration for guidance.
|
| 146 |
+
|
| 147 |
+
This method will fill automatically the following client parameters:
|
| 148 |
+
- credentials
|
| 149 |
+
- subscription_id
|
| 150 |
+
- base_url
|
| 151 |
+
- tenant_id
|
| 152 |
+
|
| 153 |
+
Parameters provided in kwargs will override parameters and be passed directly to the client.
|
| 154 |
+
|
| 155 |
+
:Example:
|
| 156 |
+
|
| 157 |
+
.. code:: python
|
| 158 |
+
|
| 159 |
+
from azure.common.client_factory import get_client_from_auth_file
|
| 160 |
+
from azure.mgmt.compute import ComputeManagementClient
|
| 161 |
+
config_dict = {
|
| 162 |
+
"clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e",
|
| 163 |
+
"clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e",
|
| 164 |
+
"subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e",
|
| 165 |
+
"tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
|
| 166 |
+
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
|
| 167 |
+
"resourceManagerEndpointUrl": "https://management.azure.com/",
|
| 168 |
+
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
|
| 169 |
+
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
|
| 170 |
+
"galleryEndpointUrl": "https://gallery.azure.com/",
|
| 171 |
+
"managementEndpointUrl": "https://management.core.windows.net/"
|
| 172 |
+
}
|
| 173 |
+
client = get_client_from_json_dict(ComputeManagementClient, config_dict)
|
| 174 |
+
|
| 175 |
+
.. versionadded:: 1.1.7
|
| 176 |
+
|
| 177 |
+
.. deprecated:: 1.1.28
|
| 178 |
+
|
| 179 |
+
.. seealso:: https://aka.ms/azsdk/python/identity/migration
|
| 180 |
+
|
| 181 |
+
:param client_class: A SDK client class
|
| 182 |
+
:param dict config_dict: A config dict.
|
| 183 |
+
:return: An instantiated client
|
| 184 |
+
"""
|
| 185 |
+
if _is_autorest_v3(client_class):
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"Auth file or JSON dict are deprecated auth approach and are not supported anymore. "
|
| 188 |
+
"See also https://aka.ms/azsdk/python/identity/migration."
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
import adal
|
| 192 |
+
from msrestazure.azure_active_directory import AdalAuthentication
|
| 193 |
+
|
| 194 |
+
is_graphrbac = client_class.__name__ == 'GraphRbacManagementClient'
|
| 195 |
+
is_keyvault = client_class.__name__ == 'KeyVaultClient'
|
| 196 |
+
parameters = {
|
| 197 |
+
'subscription_id': config_dict.get('subscriptionId'),
|
| 198 |
+
'base_url': config_dict.get('resourceManagerEndpointUrl'),
|
| 199 |
+
'tenant_id': config_dict.get('tenantId') # GraphRbac
|
| 200 |
+
}
|
| 201 |
+
if is_graphrbac:
|
| 202 |
+
parameters['base_url'] = config_dict['activeDirectoryGraphResourceId']
|
| 203 |
+
|
| 204 |
+
if 'credentials' not in kwargs:
|
| 205 |
+
# Get the right resource for Credentials
|
| 206 |
+
if is_graphrbac:
|
| 207 |
+
resource = config_dict['activeDirectoryGraphResourceId']
|
| 208 |
+
elif is_keyvault:
|
| 209 |
+
resource = "https://vault.azure.net"
|
| 210 |
+
else:
|
| 211 |
+
if "activeDirectoryResourceId" not in config_dict and 'resourceManagerEndpointUrl' not in config_dict:
|
| 212 |
+
raise ValueError("Need activeDirectoryResourceId or resourceManagerEndpointUrl key")
|
| 213 |
+
resource = config_dict.get('activeDirectoryResourceId', config_dict['resourceManagerEndpointUrl'])
|
| 214 |
+
|
| 215 |
+
authority_url = config_dict['activeDirectoryEndpointUrl']
|
| 216 |
+
is_adfs = bool(re.match('.+(/adfs|/adfs/)$', authority_url, re.I))
|
| 217 |
+
if is_adfs:
|
| 218 |
+
authority_url = authority_url.rstrip('/') # workaround: ADAL is known to reject auth urls with trailing /
|
| 219 |
+
else:
|
| 220 |
+
authority_url = authority_url + '/' + config_dict['tenantId']
|
| 221 |
+
|
| 222 |
+
context = adal.AuthenticationContext(
|
| 223 |
+
authority_url,
|
| 224 |
+
api_version=None,
|
| 225 |
+
validate_authority=not is_adfs
|
| 226 |
+
)
|
| 227 |
+
parameters['credentials'] = AdalAuthentication(
|
| 228 |
+
context.acquire_token_with_client_credentials,
|
| 229 |
+
resource,
|
| 230 |
+
config_dict['clientId'],
|
| 231 |
+
config_dict['clientSecret']
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
parameters.update(kwargs)
|
| 235 |
+
return _instantiate_client(client_class, **parameters)
|
| 236 |
+
|
| 237 |
+
def get_client_from_auth_file(client_class, auth_path=None, **kwargs):
|
| 238 |
+
"""Return a SDK client initialized with auth file.
|
| 239 |
+
|
| 240 |
+
*Disclaimer*: This is NOT the recommended approach, see https://aka.ms/azsdk/python/identity/migration for guidance.
|
| 241 |
+
|
| 242 |
+
You can specific the file path directly, or fill the environment variable AZURE_AUTH_LOCATION.
|
| 243 |
+
File must be UTF-8.
|
| 244 |
+
|
| 245 |
+
This method will fill automatically the following client parameters:
|
| 246 |
+
- credentials
|
| 247 |
+
- subscription_id
|
| 248 |
+
- base_url
|
| 249 |
+
|
| 250 |
+
Parameters provided in kwargs will override parameters and be passed directly to the client.
|
| 251 |
+
|
| 252 |
+
:Example:
|
| 253 |
+
|
| 254 |
+
.. code:: python
|
| 255 |
+
|
| 256 |
+
from azure.common.client_factory import get_client_from_auth_file
|
| 257 |
+
from azure.mgmt.compute import ComputeManagementClient
|
| 258 |
+
client = get_client_from_auth_file(ComputeManagementClient)
|
| 259 |
+
|
| 260 |
+
Example of file:
|
| 261 |
+
|
| 262 |
+
.. code:: json
|
| 263 |
+
|
| 264 |
+
{
|
| 265 |
+
"clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e",
|
| 266 |
+
"clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e",
|
| 267 |
+
"subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e",
|
| 268 |
+
"tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
|
| 269 |
+
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
|
| 270 |
+
"resourceManagerEndpointUrl": "https://management.azure.com/",
|
| 271 |
+
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
|
| 272 |
+
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
|
| 273 |
+
"galleryEndpointUrl": "https://gallery.azure.com/",
|
| 274 |
+
"managementEndpointUrl": "https://management.core.windows.net/"
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
.. versionadded:: 1.1.7
|
| 278 |
+
|
| 279 |
+
.. deprecated:: 1.1.28
|
| 280 |
+
|
| 281 |
+
.. seealso:: https://aka.ms/azsdk/python/identity/migration
|
| 282 |
+
|
| 283 |
+
:param client_class: A SDK client class
|
| 284 |
+
:param str auth_path: Path to the file.
|
| 285 |
+
:return: An instantiated client
|
| 286 |
+
:raises: KeyError if AZURE_AUTH_LOCATION is not an environment variable and no path is provided
|
| 287 |
+
:raises: FileNotFoundError if provided file path does not exists
|
| 288 |
+
:raises: json.JSONDecodeError if provided file is not JSON valid
|
| 289 |
+
:raises: UnicodeDecodeError if file is not UTF8 compliant
|
| 290 |
+
"""
|
| 291 |
+
auth_path = auth_path or os.environ['AZURE_AUTH_LOCATION']
|
| 292 |
+
|
| 293 |
+
with io.open(auth_path, 'r', encoding='utf-8-sig') as auth_fd:
|
| 294 |
+
config_dict = json.load(auth_fd)
|
| 295 |
+
return get_client_from_json_dict(client_class, config_dict, **kwargs)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/cloud.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
def get_cli_active_cloud():
|
| 8 |
+
"""Return a CLI active cloud.
|
| 9 |
+
|
| 10 |
+
*Disclaimer*: This method is not working for azure-cli-core>=2.21.0 (released in March 2021).
|
| 11 |
+
|
| 12 |
+
.. versionadded:: 1.1.6
|
| 13 |
+
|
| 14 |
+
.. deprecated:: 1.1.28
|
| 15 |
+
|
| 16 |
+
:return: A CLI Cloud
|
| 17 |
+
:rtype: azure.cli.core.cloud.Cloud
|
| 18 |
+
:raises: ImportError if azure-cli-core package is not available
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from azure.cli.core.cloud import get_active_cloud
|
| 23 |
+
except ImportError:
|
| 24 |
+
raise ImportError(
|
| 25 |
+
"The public API of azure-cli-core has been deprecated starting 2.21.0, " +
|
| 26 |
+
"and this method no longer can return a cloud instance. " +
|
| 27 |
+
"If you want to use this method, you need to install 'azure-cli-core<2.21.0'. " +
|
| 28 |
+
"You may corrupt data if you use current CLI and old azure-cli-core."
|
| 29 |
+
)
|
| 30 |
+
return get_active_cloud()
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/credentials.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
|
| 7 |
+
import os.path
|
| 8 |
+
import time
|
| 9 |
+
import warnings
|
| 10 |
+
try:
|
| 11 |
+
from azure.core.credentials import AccessToken as _AccessToken
|
| 12 |
+
except ImportError:
|
| 13 |
+
_AccessToken = None
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_cli_profile():
|
| 17 |
+
"""Return a CLI profile class.
|
| 18 |
+
|
| 19 |
+
*Disclaimer*: This method is not working for azure-cli-core>=2.21.0 (released in March 2021).
|
| 20 |
+
|
| 21 |
+
.. versionadded:: 1.1.6
|
| 22 |
+
|
| 23 |
+
.. deprecated:: 1.1.28
|
| 24 |
+
|
| 25 |
+
:return: A CLI Profile
|
| 26 |
+
:rtype: azure.cli.core._profile.Profile
|
| 27 |
+
:raises: ImportError if azure-cli-core package is not available
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from azure.cli.core._profile import Profile
|
| 32 |
+
from azure.cli.core._session import ACCOUNT
|
| 33 |
+
from azure.cli.core._environment import get_config_dir
|
| 34 |
+
except ImportError:
|
| 35 |
+
raise ImportError(
|
| 36 |
+
"The public API of azure-cli-core has been deprecated starting 2.21.0, " +
|
| 37 |
+
"and this method can no longer return a profile. " +
|
| 38 |
+
"If you need to load CLI profile using this method, you need to install 'azure-cli-core<2.21.0'. " +
|
| 39 |
+
"You may corrupt data if you use current CLI and old azure-cli-core."
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
azure_folder = get_config_dir()
|
| 43 |
+
ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json'))
|
| 44 |
+
return Profile(storage=ACCOUNT)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class _CliCredentials(object):
|
| 48 |
+
"""A wrapper of CLI credentials type that implements the azure-core credential protocol AND
|
| 49 |
+
the msrestazure protocol.
|
| 50 |
+
|
| 51 |
+
:param cli_profile: The CLI profile instance
|
| 52 |
+
:param resource: The resource to use in "msrestazure" mode (ignored otherwise)
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
_DEFAULT_PREFIX = "/.default"
|
| 56 |
+
|
| 57 |
+
def __init__(self, cli_profile, resource):
|
| 58 |
+
self._profile = cli_profile
|
| 59 |
+
self._resource = resource
|
| 60 |
+
self._cred_dict = {}
|
| 61 |
+
|
| 62 |
+
def _get_cred(self, resource):
|
| 63 |
+
if not resource in self._cred_dict:
|
| 64 |
+
credentials, _, _ = self._profile.get_login_credentials(resource=resource)
|
| 65 |
+
self._cred_dict[resource] = credentials
|
| 66 |
+
return self._cred_dict[resource]
|
| 67 |
+
|
| 68 |
+
def get_token(self, *scopes, **kwargs): # pylint:disable=unused-argument
|
| 69 |
+
if _AccessToken is None: # import failed
|
| 70 |
+
raise ImportError("You need to install 'azure-core' to use CLI credentials in this context")
|
| 71 |
+
|
| 72 |
+
if len(scopes) != 1:
|
| 73 |
+
raise ValueError("Multiple scopes are not supported: {}".format(scopes))
|
| 74 |
+
scope = scopes[0]
|
| 75 |
+
if scope.endswith(self._DEFAULT_PREFIX):
|
| 76 |
+
resource = scope[:-len(self._DEFAULT_PREFIX)]
|
| 77 |
+
else:
|
| 78 |
+
resource = scope
|
| 79 |
+
|
| 80 |
+
credentials = self._get_cred(resource)
|
| 81 |
+
# _token_retriever() not accessible after azure-cli-core 2.21.0
|
| 82 |
+
_, token, fulltoken = credentials._token_retriever() # pylint:disable=protected-access
|
| 83 |
+
|
| 84 |
+
return _AccessToken(token, int(fulltoken['expiresIn'] + time.time()))
|
| 85 |
+
|
| 86 |
+
def signed_session(self, session=None):
|
| 87 |
+
credentials = self._get_cred(self._resource)
|
| 88 |
+
return credentials.signed_session(session)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_azure_cli_credentials(resource=None, with_tenant=False):
|
| 92 |
+
"""Return Credentials and default SubscriptionID of current loaded profile of the CLI.
|
| 93 |
+
|
| 94 |
+
*Disclaimer*: This method is not working for azure-cli-core>=2.21.0 (released in March 2021).
|
| 95 |
+
It is now recommended to authenticate using https://pypi.org/project/azure-identity/ and AzureCliCredential.
|
| 96 |
+
See example code below:
|
| 97 |
+
|
| 98 |
+
.. code:: python
|
| 99 |
+
|
| 100 |
+
from azure.identity import AzureCliCredential
|
| 101 |
+
from azure.mgmt.compute import ComputeManagementClient
|
| 102 |
+
client = ComputeManagementClient(AzureCliCredential(), subscription_id)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
For compatible azure-cli-core version (< 2.20.0), credentials will be the "az login" command:
|
| 106 |
+
https://docs.microsoft.com/cli/azure/authenticate-azure-cli
|
| 107 |
+
|
| 108 |
+
Default subscription ID is either the only one you have, or you can define it:
|
| 109 |
+
https://docs.microsoft.com/cli/azure/manage-azure-subscriptions-azure-cli
|
| 110 |
+
|
| 111 |
+
.. versionadded:: 1.1.6
|
| 112 |
+
|
| 113 |
+
.. deprecated:: 1.1.28
|
| 114 |
+
|
| 115 |
+
.. seealso:: https://aka.ms/azsdk/python/identity/migration
|
| 116 |
+
|
| 117 |
+
:param str resource: The alternative resource for credentials if not ARM (GraphRBac, etc.)
|
| 118 |
+
:param bool with_tenant: If True, return a three-tuple with last as tenant ID
|
| 119 |
+
:return: tuple of Credentials and SubscriptionID (and tenant ID if with_tenant)
|
| 120 |
+
:rtype: tuple
|
| 121 |
+
"""
|
| 122 |
+
warnings.warn(
|
| 123 |
+
"get_client_from_cli_profile is deprecated, please use azure-identity and AzureCliCredential instead. " +
|
| 124 |
+
"https://aka.ms/azsdk/python/identity/migration.",
|
| 125 |
+
DeprecationWarning
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
azure_cli_core_check_failed = False
|
| 129 |
+
try:
|
| 130 |
+
import azure.cli.core
|
| 131 |
+
minor_version = int(azure.cli.core.__version__.split(".")[1])
|
| 132 |
+
if minor_version >= 21:
|
| 133 |
+
azure_cli_core_check_failed = True
|
| 134 |
+
except Exception:
|
| 135 |
+
azure_cli_core_check_failed = True
|
| 136 |
+
|
| 137 |
+
if azure_cli_core_check_failed:
|
| 138 |
+
raise NotImplementedError(
|
| 139 |
+
"The public API of azure-cli-core has been deprecated starting 2.21.0, " +
|
| 140 |
+
"and this method can no longer return a valid credential. " +
|
| 141 |
+
"If you need to still use this method, you need to install 'azure-cli-core<2.21.0'. " +
|
| 142 |
+
"You may corrupt data if you use current CLI and old azure-cli-core. " +
|
| 143 |
+
"See also: https://aka.ms/azsdk/python/identity/migration"
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
profile = get_cli_profile()
|
| 147 |
+
cred, subscription_id, tenant_id = profile.get_login_credentials(resource=resource)
|
| 148 |
+
cred = _CliCredentials(profile, resource)
|
| 149 |
+
if with_tenant:
|
| 150 |
+
return cred, subscription_id, tenant_id
|
| 151 |
+
else:
|
| 152 |
+
return cred, subscription_id
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
from msrest.authentication import (
|
| 157 |
+
BasicAuthentication,
|
| 158 |
+
BasicTokenAuthentication,
|
| 159 |
+
OAuthTokenAuthentication
|
| 160 |
+
)
|
| 161 |
+
except ImportError:
|
| 162 |
+
raise ImportError("You need to install 'msrest' to use this feature")
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
from msrestazure.azure_active_directory import (
|
| 166 |
+
InteractiveCredentials,
|
| 167 |
+
ServicePrincipalCredentials,
|
| 168 |
+
UserPassCredentials
|
| 169 |
+
)
|
| 170 |
+
except ImportError:
|
| 171 |
+
raise ImportError("You need to install 'msrestazure' to use this feature")
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/common/exceptions.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#-------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
#--------------------------------------------------------------------------
|
| 6 |
+
try:
|
| 7 |
+
from msrest.exceptions import (
|
| 8 |
+
ClientException,
|
| 9 |
+
SerializationError,
|
| 10 |
+
DeserializationError,
|
| 11 |
+
TokenExpiredError,
|
| 12 |
+
ClientRequestError,
|
| 13 |
+
AuthenticationError,
|
| 14 |
+
HttpOperationError,
|
| 15 |
+
)
|
| 16 |
+
except ImportError:
|
| 17 |
+
raise ImportError("You need to install 'msrest' to use this feature")
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
from msrestazure.azure_exceptions import CloudError
|
| 21 |
+
except ImportError:
|
| 22 |
+
raise ImportError("You need to install 'msrestazure' to use this feature")
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
from ._version import VERSION
|
| 28 |
+
|
| 29 |
+
__version__ = VERSION
|
| 30 |
+
|
| 31 |
+
from ._pipeline_client import PipelineClient
|
| 32 |
+
from ._match_conditions import MatchConditions
|
| 33 |
+
from ._enum_meta import CaseInsensitiveEnumMeta
|
| 34 |
+
from ._pipeline_client_async import AsyncPipelineClient
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
"PipelineClient",
|
| 38 |
+
"MatchConditions",
|
| 39 |
+
"CaseInsensitiveEnumMeta",
|
| 40 |
+
"AsyncPipelineClient",
|
| 41 |
+
]
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_enum_meta.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from typing import Any
|
| 27 |
+
from enum import EnumMeta, Enum
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class CaseInsensitiveEnumMeta(EnumMeta):
|
| 31 |
+
"""Enum metaclass to allow for interoperability with case-insensitive strings.
|
| 32 |
+
|
| 33 |
+
Consuming this metaclass in an SDK should be done in the following manner:
|
| 34 |
+
|
| 35 |
+
.. code-block:: python
|
| 36 |
+
|
| 37 |
+
from enum import Enum
|
| 38 |
+
from azure.core import CaseInsensitiveEnumMeta
|
| 39 |
+
|
| 40 |
+
class MyCustomEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta):
|
| 41 |
+
FOO = 'foo'
|
| 42 |
+
BAR = 'bar'
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __getitem__(cls, name: str) -> Any:
|
| 47 |
+
# disabling pylint bc of pylint bug https://github.com/PyCQA/astroid/issues/713
|
| 48 |
+
return super(CaseInsensitiveEnumMeta, cls).__getitem__(name.upper()) # pylint: disable=no-value-for-parameter
|
| 49 |
+
|
| 50 |
+
def __getattr__(cls, name: str) -> Enum:
|
| 51 |
+
"""Return the enum member matching `name`.
|
| 52 |
+
|
| 53 |
+
We use __getattr__ instead of descriptors or inserting into the enum
|
| 54 |
+
class' __dict__ in order to support `name` and `value` being both
|
| 55 |
+
properties for enum members (which live in the class' __dict__) and
|
| 56 |
+
enum members themselves.
|
| 57 |
+
|
| 58 |
+
:param str name: The name of the enum member to retrieve.
|
| 59 |
+
:rtype: ~azure.core.CaseInsensitiveEnumMeta
|
| 60 |
+
:return: The enum member matching `name`.
|
| 61 |
+
:raises AttributeError: If `name` is not a valid enum member.
|
| 62 |
+
"""
|
| 63 |
+
try:
|
| 64 |
+
return cls._member_map_[name.upper()]
|
| 65 |
+
except KeyError as err:
|
| 66 |
+
raise AttributeError(name) from err
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_match_conditions.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
from enum import Enum
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class MatchConditions(Enum):
|
| 31 |
+
"""An enum to describe match conditions."""
|
| 32 |
+
|
| 33 |
+
Unconditionally = 1
|
| 34 |
+
"""Matches any condition"""
|
| 35 |
+
|
| 36 |
+
IfNotModified = 2
|
| 37 |
+
"""If the target object is not modified. Usually it maps to etag=<specific etag>"""
|
| 38 |
+
|
| 39 |
+
IfModified = 3
|
| 40 |
+
"""Only if the target object is modified. Usually it maps to etag!=<specific etag>"""
|
| 41 |
+
|
| 42 |
+
IfPresent = 4
|
| 43 |
+
"""If the target object exists. Usually it maps to etag='*'"""
|
| 44 |
+
|
| 45 |
+
IfMissing = 5
|
| 46 |
+
"""If the target object does not exist. Usually it maps to etag!='*'"""
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_pipeline_client.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
import logging
|
| 28 |
+
from collections.abc import Iterable
|
| 29 |
+
from typing import TypeVar, Generic, Optional, Any
|
| 30 |
+
from .configuration import Configuration
|
| 31 |
+
from .pipeline import Pipeline
|
| 32 |
+
from .pipeline.transport._base import PipelineClientBase
|
| 33 |
+
from .pipeline.transport import HttpTransport
|
| 34 |
+
from .pipeline.policies import (
|
| 35 |
+
ContentDecodePolicy,
|
| 36 |
+
DistributedTracingPolicy,
|
| 37 |
+
HttpLoggingPolicy,
|
| 38 |
+
RequestIdPolicy,
|
| 39 |
+
RetryPolicy,
|
| 40 |
+
SensitiveHeaderCleanupPolicy,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
HTTPResponseType = TypeVar("HTTPResponseType")
|
| 44 |
+
HTTPRequestType = TypeVar("HTTPRequestType")
|
| 45 |
+
|
| 46 |
+
_LOGGER = logging.getLogger(__name__)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class PipelineClient(PipelineClientBase, Generic[HTTPRequestType, HTTPResponseType]):
|
| 50 |
+
"""Service client core methods.
|
| 51 |
+
|
| 52 |
+
Builds a Pipeline client.
|
| 53 |
+
|
| 54 |
+
:param str base_url: URL for the request.
|
| 55 |
+
:keyword ~azure.core.configuration.Configuration config: If omitted, the standard configuration is used.
|
| 56 |
+
:keyword Pipeline pipeline: If omitted, a Pipeline object is created and returned.
|
| 57 |
+
:keyword list[HTTPPolicy] policies: If omitted, the standard policies of the configuration object is used.
|
| 58 |
+
:keyword per_call_policies: If specified, the policies will be added into the policy list before RetryPolicy
|
| 59 |
+
:paramtype per_call_policies: Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]
|
| 60 |
+
:keyword per_retry_policies: If specified, the policies will be added into the policy list after RetryPolicy
|
| 61 |
+
:paramtype per_retry_policies: Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]
|
| 62 |
+
:keyword HttpTransport transport: If omitted, RequestsTransport is used for synchronous transport.
|
| 63 |
+
:return: A pipeline object.
|
| 64 |
+
:rtype: ~azure.core.pipeline.Pipeline
|
| 65 |
+
|
| 66 |
+
.. admonition:: Example:
|
| 67 |
+
|
| 68 |
+
.. literalinclude:: ../samples/test_example_sync.py
|
| 69 |
+
:start-after: [START build_pipeline_client]
|
| 70 |
+
:end-before: [END build_pipeline_client]
|
| 71 |
+
:language: python
|
| 72 |
+
:dedent: 4
|
| 73 |
+
:caption: Builds the pipeline client.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def __init__(
|
| 77 |
+
self,
|
| 78 |
+
base_url: str,
|
| 79 |
+
*,
|
| 80 |
+
pipeline: Optional[Pipeline[HTTPRequestType, HTTPResponseType]] = None,
|
| 81 |
+
config: Optional[Configuration[HTTPRequestType, HTTPResponseType]] = None,
|
| 82 |
+
**kwargs: Any,
|
| 83 |
+
):
|
| 84 |
+
super(PipelineClient, self).__init__(base_url)
|
| 85 |
+
self._config: Configuration[HTTPRequestType, HTTPResponseType] = config or Configuration(**kwargs)
|
| 86 |
+
self._base_url = base_url
|
| 87 |
+
|
| 88 |
+
self._pipeline = pipeline or self._build_pipeline(self._config, **kwargs)
|
| 89 |
+
|
| 90 |
+
def __enter__(self) -> PipelineClient[HTTPRequestType, HTTPResponseType]:
|
| 91 |
+
self._pipeline.__enter__()
|
| 92 |
+
return self
|
| 93 |
+
|
| 94 |
+
def __exit__(self, *exc_details: Any) -> None:
|
| 95 |
+
self._pipeline.__exit__(*exc_details)
|
| 96 |
+
|
| 97 |
+
def close(self) -> None:
|
| 98 |
+
self.__exit__()
|
| 99 |
+
|
| 100 |
+
def _build_pipeline(
|
| 101 |
+
self,
|
| 102 |
+
config: Configuration[HTTPRequestType, HTTPResponseType],
|
| 103 |
+
*,
|
| 104 |
+
transport: Optional[HttpTransport[HTTPRequestType, HTTPResponseType]] = None,
|
| 105 |
+
policies=None,
|
| 106 |
+
per_call_policies=None,
|
| 107 |
+
per_retry_policies=None,
|
| 108 |
+
**kwargs,
|
| 109 |
+
) -> Pipeline[HTTPRequestType, HTTPResponseType]:
|
| 110 |
+
per_call_policies = per_call_policies or []
|
| 111 |
+
per_retry_policies = per_retry_policies or []
|
| 112 |
+
|
| 113 |
+
if policies is None: # [] is a valid policy list
|
| 114 |
+
policies = [
|
| 115 |
+
config.request_id_policy or RequestIdPolicy(**kwargs),
|
| 116 |
+
config.headers_policy,
|
| 117 |
+
config.user_agent_policy,
|
| 118 |
+
config.proxy_policy,
|
| 119 |
+
ContentDecodePolicy(**kwargs),
|
| 120 |
+
]
|
| 121 |
+
if isinstance(per_call_policies, Iterable):
|
| 122 |
+
policies.extend(per_call_policies)
|
| 123 |
+
else:
|
| 124 |
+
policies.append(per_call_policies)
|
| 125 |
+
|
| 126 |
+
policies.extend(
|
| 127 |
+
[
|
| 128 |
+
config.redirect_policy,
|
| 129 |
+
config.retry_policy,
|
| 130 |
+
config.authentication_policy,
|
| 131 |
+
config.custom_hook_policy,
|
| 132 |
+
]
|
| 133 |
+
)
|
| 134 |
+
if isinstance(per_retry_policies, Iterable):
|
| 135 |
+
policies.extend(per_retry_policies)
|
| 136 |
+
else:
|
| 137 |
+
policies.append(per_retry_policies)
|
| 138 |
+
|
| 139 |
+
policies.extend(
|
| 140 |
+
[
|
| 141 |
+
config.logging_policy,
|
| 142 |
+
DistributedTracingPolicy(**kwargs),
|
| 143 |
+
SensitiveHeaderCleanupPolicy(**kwargs) if config.redirect_policy else None,
|
| 144 |
+
config.http_logging_policy or HttpLoggingPolicy(**kwargs),
|
| 145 |
+
]
|
| 146 |
+
)
|
| 147 |
+
else:
|
| 148 |
+
if isinstance(per_call_policies, Iterable):
|
| 149 |
+
per_call_policies_list = list(per_call_policies)
|
| 150 |
+
else:
|
| 151 |
+
per_call_policies_list = [per_call_policies]
|
| 152 |
+
per_call_policies_list.extend(policies)
|
| 153 |
+
policies = per_call_policies_list
|
| 154 |
+
|
| 155 |
+
if isinstance(per_retry_policies, Iterable):
|
| 156 |
+
per_retry_policies_list = list(per_retry_policies)
|
| 157 |
+
else:
|
| 158 |
+
per_retry_policies_list = [per_retry_policies]
|
| 159 |
+
if len(per_retry_policies_list) > 0:
|
| 160 |
+
index_of_retry = -1
|
| 161 |
+
for index, policy in enumerate(policies):
|
| 162 |
+
if isinstance(policy, RetryPolicy):
|
| 163 |
+
index_of_retry = index
|
| 164 |
+
if index_of_retry == -1:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"Failed to add per_retry_policies; no RetryPolicy found in the supplied list of policies. "
|
| 167 |
+
)
|
| 168 |
+
policies_1 = policies[: index_of_retry + 1]
|
| 169 |
+
policies_2 = policies[index_of_retry + 1 :]
|
| 170 |
+
policies_1.extend(per_retry_policies_list)
|
| 171 |
+
policies_1.extend(policies_2)
|
| 172 |
+
policies = policies_1
|
| 173 |
+
|
| 174 |
+
if transport is None:
|
| 175 |
+
# Use private import for better typing, mypy and pyright don't like PEP562
|
| 176 |
+
from .pipeline.transport._requests_basic import RequestsTransport
|
| 177 |
+
|
| 178 |
+
transport = RequestsTransport(**kwargs)
|
| 179 |
+
|
| 180 |
+
return Pipeline(transport, policies)
|
| 181 |
+
|
| 182 |
+
def send_request(self, request: HTTPRequestType, *, stream: bool = False, **kwargs: Any) -> HTTPResponseType:
|
| 183 |
+
"""Method that runs the network request through the client's chained policies.
|
| 184 |
+
|
| 185 |
+
>>> from azure.core.rest import HttpRequest
|
| 186 |
+
>>> request = HttpRequest('GET', 'http://www.example.com')
|
| 187 |
+
<HttpRequest [GET], url: 'http://www.example.com'>
|
| 188 |
+
>>> response = client.send_request(request)
|
| 189 |
+
<HttpResponse: 200 OK>
|
| 190 |
+
|
| 191 |
+
:param request: The network request you want to make. Required.
|
| 192 |
+
:type request: ~azure.core.rest.HttpRequest
|
| 193 |
+
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
|
| 194 |
+
:return: The response of your network call. Does not do error handling on your response.
|
| 195 |
+
:rtype: ~azure.core.rest.HttpResponse
|
| 196 |
+
"""
|
| 197 |
+
return_pipeline_response = kwargs.pop("_return_pipeline_response", False)
|
| 198 |
+
pipeline_response = self._pipeline.run(request, stream=stream, **kwargs) # pylint: disable=protected-access
|
| 199 |
+
if return_pipeline_response:
|
| 200 |
+
return pipeline_response # type: ignore # This is a private API we don't want to type in signature
|
| 201 |
+
return pipeline_response.http_response
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_pipeline_client_async.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
import logging
|
| 28 |
+
import collections.abc
|
| 29 |
+
from typing import (
|
| 30 |
+
Any,
|
| 31 |
+
Awaitable,
|
| 32 |
+
TypeVar,
|
| 33 |
+
AsyncContextManager,
|
| 34 |
+
Generator,
|
| 35 |
+
Generic,
|
| 36 |
+
Optional,
|
| 37 |
+
Type,
|
| 38 |
+
cast,
|
| 39 |
+
)
|
| 40 |
+
from types import TracebackType
|
| 41 |
+
from .configuration import Configuration
|
| 42 |
+
from .pipeline import AsyncPipeline
|
| 43 |
+
from .pipeline.transport._base import PipelineClientBase
|
| 44 |
+
from .pipeline.policies import (
|
| 45 |
+
ContentDecodePolicy,
|
| 46 |
+
DistributedTracingPolicy,
|
| 47 |
+
HttpLoggingPolicy,
|
| 48 |
+
RequestIdPolicy,
|
| 49 |
+
AsyncRetryPolicy,
|
| 50 |
+
SensitiveHeaderCleanupPolicy,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
HTTPRequestType = TypeVar("HTTPRequestType")
|
| 55 |
+
AsyncHTTPResponseType = TypeVar("AsyncHTTPResponseType", bound="AsyncContextManager")
|
| 56 |
+
|
| 57 |
+
_LOGGER = logging.getLogger(__name__)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class _Coroutine(Awaitable[AsyncHTTPResponseType]):
|
| 61 |
+
"""Wrapper to get both context manager and awaitable in place.
|
| 62 |
+
|
| 63 |
+
Naming it "_Coroutine" because if you don't await it makes the error message easier:
|
| 64 |
+
>>> result = client.send_request(request)
|
| 65 |
+
>>> result.text()
|
| 66 |
+
AttributeError: '_Coroutine' object has no attribute 'text'
|
| 67 |
+
|
| 68 |
+
Indeed, the message for calling a coroutine without waiting would be:
|
| 69 |
+
AttributeError: 'coroutine' object has no attribute 'text'
|
| 70 |
+
|
| 71 |
+
This allows the dev to either use the "async with" syntax, or simply the object directly.
|
| 72 |
+
It's also why "send_request" is not declared as async, since it couldn't be both easily.
|
| 73 |
+
|
| 74 |
+
"wrapped" must be an awaitable object that returns an object implements the async context manager protocol.
|
| 75 |
+
|
| 76 |
+
This permits this code to work for both following requests.
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
from azure.core import AsyncPipelineClient
|
| 80 |
+
from azure.core.rest import HttpRequest
|
| 81 |
+
|
| 82 |
+
async def main():
|
| 83 |
+
|
| 84 |
+
request = HttpRequest("GET", "https://httpbin.org/user-agent")
|
| 85 |
+
async with AsyncPipelineClient("https://httpbin.org/") as client:
|
| 86 |
+
# Can be used directly
|
| 87 |
+
result = await client.send_request(request)
|
| 88 |
+
print(result.text())
|
| 89 |
+
|
| 90 |
+
# Can be used as an async context manager
|
| 91 |
+
async with client.send_request(request) as result:
|
| 92 |
+
print(result.text())
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
:param wrapped: Must be an awaitable the returns an async context manager that supports async "close()"
|
| 96 |
+
:type wrapped: awaitable[AsyncHTTPResponseType]
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
def __init__(self, wrapped: Awaitable[AsyncHTTPResponseType]) -> None:
|
| 100 |
+
super().__init__()
|
| 101 |
+
self._wrapped = wrapped
|
| 102 |
+
# If someone tries to use the object without awaiting, they will get a
|
| 103 |
+
# AttributeError: '_Coroutine' object has no attribute 'text'
|
| 104 |
+
self._response: AsyncHTTPResponseType = cast(AsyncHTTPResponseType, None)
|
| 105 |
+
|
| 106 |
+
def __await__(self) -> Generator[Any, None, AsyncHTTPResponseType]:
|
| 107 |
+
return self._wrapped.__await__()
|
| 108 |
+
|
| 109 |
+
async def __aenter__(self) -> AsyncHTTPResponseType:
|
| 110 |
+
self._response = await self
|
| 111 |
+
return self._response
|
| 112 |
+
|
| 113 |
+
async def __aexit__(
|
| 114 |
+
self,
|
| 115 |
+
exc_type: Optional[Type[BaseException]] = None,
|
| 116 |
+
exc_value: Optional[BaseException] = None,
|
| 117 |
+
traceback: Optional[TracebackType] = None,
|
| 118 |
+
) -> None:
|
| 119 |
+
await self._response.__aexit__(exc_type, exc_value, traceback)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class AsyncPipelineClient(
|
| 123 |
+
PipelineClientBase,
|
| 124 |
+
AsyncContextManager["AsyncPipelineClient"],
|
| 125 |
+
Generic[HTTPRequestType, AsyncHTTPResponseType],
|
| 126 |
+
):
|
| 127 |
+
"""Service client core methods.
|
| 128 |
+
|
| 129 |
+
Builds an AsyncPipeline client.
|
| 130 |
+
|
| 131 |
+
:param str base_url: URL for the request.
|
| 132 |
+
:keyword ~azure.core.configuration.Configuration config: If omitted, the standard configuration is used.
|
| 133 |
+
:keyword Pipeline pipeline: If omitted, a Pipeline object is created and returned.
|
| 134 |
+
:keyword list[AsyncHTTPPolicy] policies: If omitted, the standard policies of the configuration object is used.
|
| 135 |
+
:keyword per_call_policies: If specified, the policies will be added into the policy list before RetryPolicy
|
| 136 |
+
:paramtype per_call_policies: Union[AsyncHTTPPolicy, SansIOHTTPPolicy,
|
| 137 |
+
list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]
|
| 138 |
+
:keyword per_retry_policies: If specified, the policies will be added into the policy list after RetryPolicy
|
| 139 |
+
:paramtype per_retry_policies: Union[AsyncHTTPPolicy, SansIOHTTPPolicy,
|
| 140 |
+
list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]
|
| 141 |
+
:keyword AsyncHttpTransport transport: If omitted, AioHttpTransport is used for asynchronous transport.
|
| 142 |
+
:return: An async pipeline object.
|
| 143 |
+
:rtype: ~azure.core.pipeline.AsyncPipeline
|
| 144 |
+
|
| 145 |
+
.. admonition:: Example:
|
| 146 |
+
|
| 147 |
+
.. literalinclude:: ../samples/test_example_async.py
|
| 148 |
+
:start-after: [START build_async_pipeline_client]
|
| 149 |
+
:end-before: [END build_async_pipeline_client]
|
| 150 |
+
:language: python
|
| 151 |
+
:dedent: 4
|
| 152 |
+
:caption: Builds the async pipeline client.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def __init__(
|
| 156 |
+
self,
|
| 157 |
+
base_url: str,
|
| 158 |
+
*,
|
| 159 |
+
pipeline: Optional[AsyncPipeline[HTTPRequestType, AsyncHTTPResponseType]] = None,
|
| 160 |
+
config: Optional[Configuration[HTTPRequestType, AsyncHTTPResponseType]] = None,
|
| 161 |
+
**kwargs: Any,
|
| 162 |
+
):
|
| 163 |
+
super(AsyncPipelineClient, self).__init__(base_url)
|
| 164 |
+
self._config: Configuration[HTTPRequestType, AsyncHTTPResponseType] = config or Configuration(**kwargs)
|
| 165 |
+
self._base_url = base_url
|
| 166 |
+
self._pipeline = pipeline or self._build_pipeline(self._config, **kwargs)
|
| 167 |
+
|
| 168 |
+
async def __aenter__(self) -> AsyncPipelineClient[HTTPRequestType, AsyncHTTPResponseType]:
|
| 169 |
+
await self._pipeline.__aenter__()
|
| 170 |
+
return self
|
| 171 |
+
|
| 172 |
+
async def __aexit__(
|
| 173 |
+
self,
|
| 174 |
+
exc_type: Optional[Type[BaseException]] = None,
|
| 175 |
+
exc_value: Optional[BaseException] = None,
|
| 176 |
+
traceback: Optional[TracebackType] = None,
|
| 177 |
+
) -> None:
|
| 178 |
+
await self._pipeline.__aexit__(exc_type, exc_value, traceback)
|
| 179 |
+
|
| 180 |
+
async def close(self) -> None:
|
| 181 |
+
await self.__aexit__()
|
| 182 |
+
|
| 183 |
+
def _build_pipeline(
|
| 184 |
+
self,
|
| 185 |
+
config: Configuration[HTTPRequestType, AsyncHTTPResponseType],
|
| 186 |
+
*,
|
| 187 |
+
policies=None,
|
| 188 |
+
per_call_policies=None,
|
| 189 |
+
per_retry_policies=None,
|
| 190 |
+
**kwargs,
|
| 191 |
+
) -> AsyncPipeline[HTTPRequestType, AsyncHTTPResponseType]:
|
| 192 |
+
transport = kwargs.get("transport")
|
| 193 |
+
per_call_policies = per_call_policies or []
|
| 194 |
+
per_retry_policies = per_retry_policies or []
|
| 195 |
+
|
| 196 |
+
if policies is None: # [] is a valid policy list
|
| 197 |
+
policies = [
|
| 198 |
+
config.request_id_policy or RequestIdPolicy(**kwargs),
|
| 199 |
+
config.headers_policy,
|
| 200 |
+
config.user_agent_policy,
|
| 201 |
+
config.proxy_policy,
|
| 202 |
+
ContentDecodePolicy(**kwargs),
|
| 203 |
+
]
|
| 204 |
+
if isinstance(per_call_policies, collections.abc.Iterable):
|
| 205 |
+
policies.extend(per_call_policies)
|
| 206 |
+
else:
|
| 207 |
+
policies.append(per_call_policies)
|
| 208 |
+
|
| 209 |
+
policies.extend(
|
| 210 |
+
[
|
| 211 |
+
config.redirect_policy,
|
| 212 |
+
config.retry_policy,
|
| 213 |
+
config.authentication_policy,
|
| 214 |
+
config.custom_hook_policy,
|
| 215 |
+
]
|
| 216 |
+
)
|
| 217 |
+
if isinstance(per_retry_policies, collections.abc.Iterable):
|
| 218 |
+
policies.extend(per_retry_policies)
|
| 219 |
+
else:
|
| 220 |
+
policies.append(per_retry_policies)
|
| 221 |
+
|
| 222 |
+
policies.extend(
|
| 223 |
+
[
|
| 224 |
+
config.logging_policy,
|
| 225 |
+
DistributedTracingPolicy(**kwargs),
|
| 226 |
+
SensitiveHeaderCleanupPolicy(**kwargs) if config.redirect_policy else None,
|
| 227 |
+
config.http_logging_policy or HttpLoggingPolicy(**kwargs),
|
| 228 |
+
]
|
| 229 |
+
)
|
| 230 |
+
else:
|
| 231 |
+
if isinstance(per_call_policies, collections.abc.Iterable):
|
| 232 |
+
per_call_policies_list = list(per_call_policies)
|
| 233 |
+
else:
|
| 234 |
+
per_call_policies_list = [per_call_policies]
|
| 235 |
+
per_call_policies_list.extend(policies)
|
| 236 |
+
policies = per_call_policies_list
|
| 237 |
+
if isinstance(per_retry_policies, collections.abc.Iterable):
|
| 238 |
+
per_retry_policies_list = list(per_retry_policies)
|
| 239 |
+
else:
|
| 240 |
+
per_retry_policies_list = [per_retry_policies]
|
| 241 |
+
if len(per_retry_policies_list) > 0:
|
| 242 |
+
index_of_retry = -1
|
| 243 |
+
for index, policy in enumerate(policies):
|
| 244 |
+
if isinstance(policy, AsyncRetryPolicy):
|
| 245 |
+
index_of_retry = index
|
| 246 |
+
if index_of_retry == -1:
|
| 247 |
+
raise ValueError(
|
| 248 |
+
"Failed to add per_retry_policies; no RetryPolicy found in the supplied list of policies. "
|
| 249 |
+
)
|
| 250 |
+
policies_1 = policies[: index_of_retry + 1]
|
| 251 |
+
policies_2 = policies[index_of_retry + 1 :]
|
| 252 |
+
policies_1.extend(per_retry_policies_list)
|
| 253 |
+
policies_1.extend(policies_2)
|
| 254 |
+
policies = policies_1
|
| 255 |
+
|
| 256 |
+
if not transport:
|
| 257 |
+
# Use private import for better typing, mypy and pyright don't like PEP562
|
| 258 |
+
from .pipeline.transport._aiohttp import AioHttpTransport
|
| 259 |
+
|
| 260 |
+
transport = AioHttpTransport(**kwargs)
|
| 261 |
+
|
| 262 |
+
return AsyncPipeline[HTTPRequestType, AsyncHTTPResponseType](transport, policies)
|
| 263 |
+
|
| 264 |
+
async def _make_pipeline_call(self, request: HTTPRequestType, **kwargs) -> AsyncHTTPResponseType:
|
| 265 |
+
return_pipeline_response = kwargs.pop("_return_pipeline_response", False)
|
| 266 |
+
pipeline_response = await self._pipeline.run(request, **kwargs) # pylint: disable=protected-access
|
| 267 |
+
if return_pipeline_response:
|
| 268 |
+
return pipeline_response # type: ignore # This is a private API we don't want to type in signature
|
| 269 |
+
return pipeline_response.http_response
|
| 270 |
+
|
| 271 |
+
def send_request(
|
| 272 |
+
self, request: HTTPRequestType, *, stream: bool = False, **kwargs: Any
|
| 273 |
+
) -> Awaitable[AsyncHTTPResponseType]:
|
| 274 |
+
"""Method that runs the network request through the client's chained policies.
|
| 275 |
+
|
| 276 |
+
>>> from azure.core.rest import HttpRequest
|
| 277 |
+
>>> request = HttpRequest('GET', 'http://www.example.com')
|
| 278 |
+
<HttpRequest [GET], url: 'http://www.example.com'>
|
| 279 |
+
>>> response = await client.send_request(request)
|
| 280 |
+
<AsyncHttpResponse: 200 OK>
|
| 281 |
+
|
| 282 |
+
:param request: The network request you want to make. Required.
|
| 283 |
+
:type request: ~azure.core.rest.HttpRequest
|
| 284 |
+
:keyword bool stream: Whether the response payload will be streamed. Defaults to False.
|
| 285 |
+
:return: The response of your network call. Does not do error handling on your response.
|
| 286 |
+
:rtype: ~azure.core.rest.AsyncHttpResponse
|
| 287 |
+
"""
|
| 288 |
+
wrapped = self._make_pipeline_call(request, stream=stream, **kwargs)
|
| 289 |
+
return _Coroutine(wrapped=wrapped)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/_version.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
#
|
| 7 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 8 |
+
# Changes may cause incorrect behavior and will be lost if the code is
|
| 9 |
+
# regenerated.
|
| 10 |
+
# --------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
VERSION = "1.30.1"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/async_paging.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
import collections.abc
|
| 27 |
+
import logging
|
| 28 |
+
from typing import (
|
| 29 |
+
Iterable,
|
| 30 |
+
AsyncIterator,
|
| 31 |
+
TypeVar,
|
| 32 |
+
Callable,
|
| 33 |
+
Tuple,
|
| 34 |
+
Optional,
|
| 35 |
+
Awaitable,
|
| 36 |
+
Any,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from .exceptions import AzureError
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
_LOGGER = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
ReturnType = TypeVar("ReturnType")
|
| 45 |
+
ResponseType = TypeVar("ResponseType")
|
| 46 |
+
|
| 47 |
+
__all__ = ["AsyncPageIterator", "AsyncItemPaged"]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class AsyncList(AsyncIterator[ReturnType]):
|
| 51 |
+
def __init__(self, iterable: Iterable[ReturnType]) -> None:
|
| 52 |
+
"""Change an iterable into a fake async iterator.
|
| 53 |
+
|
| 54 |
+
Could be useful to fill the async iterator contract when you get a list.
|
| 55 |
+
|
| 56 |
+
:param iterable: A sync iterable of T
|
| 57 |
+
"""
|
| 58 |
+
# Technically, if it's a real iterator, I don't need "iter"
|
| 59 |
+
# but that will cover iterable and list as well with no troubles created.
|
| 60 |
+
self._iterator = iter(iterable)
|
| 61 |
+
|
| 62 |
+
async def __anext__(self) -> ReturnType:
|
| 63 |
+
try:
|
| 64 |
+
return next(self._iterator)
|
| 65 |
+
except StopIteration as err:
|
| 66 |
+
raise StopAsyncIteration() from err
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class AsyncPageIterator(AsyncIterator[AsyncIterator[ReturnType]]):
|
| 70 |
+
def __init__(
|
| 71 |
+
self,
|
| 72 |
+
get_next: Callable[[Optional[str]], Awaitable[ResponseType]],
|
| 73 |
+
extract_data: Callable[[ResponseType], Awaitable[Tuple[str, AsyncIterator[ReturnType]]]],
|
| 74 |
+
continuation_token: Optional[str] = None,
|
| 75 |
+
) -> None:
|
| 76 |
+
"""Return an async iterator of pages.
|
| 77 |
+
|
| 78 |
+
:param get_next: Callable that take the continuation token and return a HTTP response
|
| 79 |
+
:param extract_data: Callable that take an HTTP response and return a tuple continuation token,
|
| 80 |
+
list of ReturnType
|
| 81 |
+
:param str continuation_token: The continuation token needed by get_next
|
| 82 |
+
"""
|
| 83 |
+
self._get_next = get_next
|
| 84 |
+
self._extract_data = extract_data
|
| 85 |
+
self.continuation_token = continuation_token
|
| 86 |
+
self._did_a_call_already = False
|
| 87 |
+
self._response: Optional[ResponseType] = None
|
| 88 |
+
self._current_page: Optional[AsyncIterator[ReturnType]] = None
|
| 89 |
+
|
| 90 |
+
async def __anext__(self) -> AsyncIterator[ReturnType]:
|
| 91 |
+
if self.continuation_token is None and self._did_a_call_already:
|
| 92 |
+
raise StopAsyncIteration("End of paging")
|
| 93 |
+
try:
|
| 94 |
+
self._response = await self._get_next(self.continuation_token)
|
| 95 |
+
except AzureError as error:
|
| 96 |
+
if not error.continuation_token:
|
| 97 |
+
error.continuation_token = self.continuation_token
|
| 98 |
+
raise
|
| 99 |
+
|
| 100 |
+
self._did_a_call_already = True
|
| 101 |
+
|
| 102 |
+
self.continuation_token, self._current_page = await self._extract_data(self._response)
|
| 103 |
+
|
| 104 |
+
# If current_page was a sync list, wrap it async-like
|
| 105 |
+
if isinstance(self._current_page, collections.abc.Iterable):
|
| 106 |
+
self._current_page = AsyncList(self._current_page)
|
| 107 |
+
|
| 108 |
+
return self._current_page
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class AsyncItemPaged(AsyncIterator[ReturnType]):
|
| 112 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 113 |
+
"""Return an async iterator of items.
|
| 114 |
+
|
| 115 |
+
args and kwargs will be passed to the AsyncPageIterator constructor directly,
|
| 116 |
+
except page_iterator_class
|
| 117 |
+
"""
|
| 118 |
+
self._args = args
|
| 119 |
+
self._kwargs = kwargs
|
| 120 |
+
self._page_iterator: Optional[AsyncIterator[AsyncIterator[ReturnType]]] = None
|
| 121 |
+
self._page: Optional[AsyncIterator[ReturnType]] = None
|
| 122 |
+
self._page_iterator_class = self._kwargs.pop("page_iterator_class", AsyncPageIterator)
|
| 123 |
+
|
| 124 |
+
def by_page(
|
| 125 |
+
self,
|
| 126 |
+
continuation_token: Optional[str] = None,
|
| 127 |
+
) -> AsyncIterator[AsyncIterator[ReturnType]]:
|
| 128 |
+
"""Get an async iterator of pages of objects, instead of an async iterator of objects.
|
| 129 |
+
|
| 130 |
+
:param str continuation_token:
|
| 131 |
+
An opaque continuation token. This value can be retrieved from the
|
| 132 |
+
continuation_token field of a previous generator object. If specified,
|
| 133 |
+
this generator will begin returning results from this point.
|
| 134 |
+
:returns: An async iterator of pages (themselves async iterator of objects)
|
| 135 |
+
:rtype: AsyncIterator[AsyncIterator[ReturnType]]
|
| 136 |
+
"""
|
| 137 |
+
return self._page_iterator_class(*self._args, **self._kwargs, continuation_token=continuation_token)
|
| 138 |
+
|
| 139 |
+
async def __anext__(self) -> ReturnType:
|
| 140 |
+
if self._page_iterator is None:
|
| 141 |
+
self._page_iterator = self.by_page()
|
| 142 |
+
return await self.__anext__()
|
| 143 |
+
if self._page is None:
|
| 144 |
+
# Let it raise StopAsyncIteration
|
| 145 |
+
self._page = await self._page_iterator.__anext__()
|
| 146 |
+
return await self.__anext__()
|
| 147 |
+
try:
|
| 148 |
+
return await self._page.__anext__()
|
| 149 |
+
except StopAsyncIteration:
|
| 150 |
+
self._page = None
|
| 151 |
+
return await self.__anext__()
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/configuration.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
from typing import Union, Optional, Any, Generic, TypeVar, TYPE_CHECKING
|
| 28 |
+
|
| 29 |
+
HTTPResponseType = TypeVar("HTTPResponseType")
|
| 30 |
+
HTTPRequestType = TypeVar("HTTPRequestType")
|
| 31 |
+
|
| 32 |
+
if TYPE_CHECKING:
|
| 33 |
+
from .pipeline.policies import HTTPPolicy, AsyncHTTPPolicy, SansIOHTTPPolicy
|
| 34 |
+
|
| 35 |
+
AnyPolicy = Union[
|
| 36 |
+
HTTPPolicy[HTTPRequestType, HTTPResponseType],
|
| 37 |
+
AsyncHTTPPolicy[HTTPRequestType, HTTPResponseType],
|
| 38 |
+
SansIOHTTPPolicy[HTTPRequestType, HTTPResponseType],
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Configuration(Generic[HTTPRequestType, HTTPResponseType]): # pylint: disable=too-many-instance-attributes
|
| 43 |
+
"""Provides the home for all of the configurable policies in the pipeline.
|
| 44 |
+
|
| 45 |
+
A new Configuration object provides no default policies and does not specify in what
|
| 46 |
+
order the policies will be added to the pipeline. The SDK developer must specify each
|
| 47 |
+
of the policy defaults as required by the service and use the policies in the
|
| 48 |
+
Configuration to construct the pipeline correctly, as well as inserting any
|
| 49 |
+
unexposed/non-configurable policies.
|
| 50 |
+
|
| 51 |
+
:ivar headers_policy: Provides parameters for custom or additional headers to be sent with the request.
|
| 52 |
+
:ivar proxy_policy: Provides configuration parameters for proxy.
|
| 53 |
+
:ivar redirect_policy: Provides configuration parameters for redirects.
|
| 54 |
+
:ivar retry_policy: Provides configuration parameters for retries in the pipeline.
|
| 55 |
+
:ivar custom_hook_policy: Provides configuration parameters for a custom hook.
|
| 56 |
+
:ivar logging_policy: Provides configuration parameters for logging.
|
| 57 |
+
:ivar http_logging_policy: Provides configuration parameters for HTTP specific logging.
|
| 58 |
+
:ivar user_agent_policy: Provides configuration parameters to append custom values to the
|
| 59 |
+
User-Agent header.
|
| 60 |
+
:ivar authentication_policy: Provides configuration parameters for adding a bearer token Authorization
|
| 61 |
+
header to requests.
|
| 62 |
+
:ivar request_id_policy: Provides configuration parameters for adding a request id to requests.
|
| 63 |
+
:keyword polling_interval: Polling interval while doing LRO operations, if Retry-After is not set.
|
| 64 |
+
|
| 65 |
+
.. admonition:: Example:
|
| 66 |
+
|
| 67 |
+
.. literalinclude:: ../samples/test_example_config.py
|
| 68 |
+
:start-after: [START configuration]
|
| 69 |
+
:end-before: [END configuration]
|
| 70 |
+
:language: python
|
| 71 |
+
:caption: Creates the service configuration and adds policies.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
def __init__(self, **kwargs: Any) -> None:
|
| 75 |
+
# Headers (sent with every request)
|
| 76 |
+
self.headers_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 77 |
+
|
| 78 |
+
# Proxy settings (Currently used to configure transport, could be pipeline policy instead)
|
| 79 |
+
self.proxy_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 80 |
+
|
| 81 |
+
# Redirect configuration
|
| 82 |
+
self.redirect_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 83 |
+
|
| 84 |
+
# Retry configuration
|
| 85 |
+
self.retry_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 86 |
+
|
| 87 |
+
# Custom hook configuration
|
| 88 |
+
self.custom_hook_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 89 |
+
|
| 90 |
+
# Logger configuration
|
| 91 |
+
self.logging_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 92 |
+
|
| 93 |
+
# Http logger configuration
|
| 94 |
+
self.http_logging_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 95 |
+
|
| 96 |
+
# User Agent configuration
|
| 97 |
+
self.user_agent_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 98 |
+
|
| 99 |
+
# Authentication configuration
|
| 100 |
+
self.authentication_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 101 |
+
|
| 102 |
+
# Request ID policy
|
| 103 |
+
self.request_id_policy: Optional[AnyPolicy[HTTPRequestType, HTTPResponseType]] = None
|
| 104 |
+
|
| 105 |
+
# Polling interval if no retry-after in polling calls results
|
| 106 |
+
self.polling_interval: float = kwargs.get("polling_interval", 30)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class ConnectionConfiguration:
|
| 110 |
+
"""HTTP transport connection configuration settings.
|
| 111 |
+
|
| 112 |
+
Common properties that can be configured on all transports. Found in the
|
| 113 |
+
Configuration object.
|
| 114 |
+
|
| 115 |
+
:keyword float connection_timeout: A single float in seconds for the connection timeout. Defaults to 300 seconds.
|
| 116 |
+
:keyword float read_timeout: A single float in seconds for the read timeout. Defaults to 300 seconds.
|
| 117 |
+
:keyword connection_verify: SSL certificate verification. Enabled by default. Set to False to disable,
|
| 118 |
+
alternatively can be set to the path to a CA_BUNDLE file or directory with certificates of trusted CAs.
|
| 119 |
+
:paramtype connection_verify: bool or str
|
| 120 |
+
:keyword str connection_cert: Client-side certificates. You can specify a local cert to use as client side
|
| 121 |
+
certificate, as a single file (containing the private key and the certificate) or as a tuple of both files' paths.
|
| 122 |
+
:keyword int connection_data_block_size: The block size of data sent over the connection. Defaults to 4096 bytes.
|
| 123 |
+
|
| 124 |
+
.. admonition:: Example:
|
| 125 |
+
|
| 126 |
+
.. literalinclude:: ../samples/test_example_config.py
|
| 127 |
+
:start-after: [START connection_configuration]
|
| 128 |
+
:end-before: [END connection_configuration]
|
| 129 |
+
:language: python
|
| 130 |
+
:dedent: 4
|
| 131 |
+
:caption: Configuring transport connection settings.
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def __init__(
|
| 135 |
+
self, # pylint: disable=unused-argument
|
| 136 |
+
*,
|
| 137 |
+
connection_timeout: float = 300,
|
| 138 |
+
read_timeout: float = 300,
|
| 139 |
+
connection_verify: Union[bool, str] = True,
|
| 140 |
+
connection_cert: Optional[str] = None,
|
| 141 |
+
connection_data_block_size: int = 4096,
|
| 142 |
+
**kwargs: Any,
|
| 143 |
+
) -> None:
|
| 144 |
+
self.timeout = connection_timeout
|
| 145 |
+
self.read_timeout = read_timeout
|
| 146 |
+
self.verify = connection_verify
|
| 147 |
+
self.cert = connection_cert
|
| 148 |
+
self.data_block_size = connection_data_block_size
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/credentials.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 3 |
+
# Licensed under the MIT License. See LICENSE.txt in the project root for
|
| 4 |
+
# license information.
|
| 5 |
+
# -------------------------------------------------------------------------
|
| 6 |
+
from typing import Any, NamedTuple, Optional
|
| 7 |
+
from typing_extensions import Protocol, runtime_checkable
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AccessToken(NamedTuple):
|
| 11 |
+
"""Represents an OAuth access token."""
|
| 12 |
+
|
| 13 |
+
token: str
|
| 14 |
+
expires_on: int
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
AccessToken.token.__doc__ = """The token string."""
|
| 18 |
+
AccessToken.expires_on.__doc__ = """The token's expiration time in Unix time."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@runtime_checkable
|
| 22 |
+
class TokenCredential(Protocol):
|
| 23 |
+
"""Protocol for classes able to provide OAuth tokens."""
|
| 24 |
+
|
| 25 |
+
def get_token(
|
| 26 |
+
self,
|
| 27 |
+
*scopes: str,
|
| 28 |
+
claims: Optional[str] = None,
|
| 29 |
+
tenant_id: Optional[str] = None,
|
| 30 |
+
enable_cae: bool = False,
|
| 31 |
+
**kwargs: Any
|
| 32 |
+
) -> AccessToken:
|
| 33 |
+
"""Request an access token for `scopes`.
|
| 34 |
+
|
| 35 |
+
:param str scopes: The type of access needed.
|
| 36 |
+
|
| 37 |
+
:keyword str claims: Additional claims required in the token, such as those returned in a resource
|
| 38 |
+
provider's claims challenge following an authorization failure.
|
| 39 |
+
:keyword str tenant_id: Optional tenant to include in the token request.
|
| 40 |
+
:keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) for the requested
|
| 41 |
+
token. Defaults to False.
|
| 42 |
+
|
| 43 |
+
:rtype: AccessToken
|
| 44 |
+
:return: An AccessToken instance containing the token string and its expiration time in Unix time.
|
| 45 |
+
"""
|
| 46 |
+
...
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AzureNamedKey(NamedTuple):
|
| 50 |
+
"""Represents a name and key pair."""
|
| 51 |
+
|
| 52 |
+
name: str
|
| 53 |
+
key: str
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
__all__ = [
|
| 57 |
+
"AzureKeyCredential",
|
| 58 |
+
"AzureSasCredential",
|
| 59 |
+
"AccessToken",
|
| 60 |
+
"AzureNamedKeyCredential",
|
| 61 |
+
"TokenCredential",
|
| 62 |
+
]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class AzureKeyCredential:
|
| 66 |
+
"""Credential type used for authenticating to an Azure service.
|
| 67 |
+
It provides the ability to update the key without creating a new client.
|
| 68 |
+
|
| 69 |
+
:param str key: The key used to authenticate to an Azure service
|
| 70 |
+
:raises: TypeError
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(self, key: str) -> None:
|
| 74 |
+
if not isinstance(key, str):
|
| 75 |
+
raise TypeError("key must be a string.")
|
| 76 |
+
self._key = key
|
| 77 |
+
|
| 78 |
+
@property
|
| 79 |
+
def key(self) -> str:
|
| 80 |
+
"""The value of the configured key.
|
| 81 |
+
|
| 82 |
+
:rtype: str
|
| 83 |
+
:return: The value of the configured key.
|
| 84 |
+
"""
|
| 85 |
+
return self._key
|
| 86 |
+
|
| 87 |
+
def update(self, key: str) -> None:
|
| 88 |
+
"""Update the key.
|
| 89 |
+
|
| 90 |
+
This can be used when you've regenerated your service key and want
|
| 91 |
+
to update long-lived clients.
|
| 92 |
+
|
| 93 |
+
:param str key: The key used to authenticate to an Azure service
|
| 94 |
+
:raises: ValueError or TypeError
|
| 95 |
+
"""
|
| 96 |
+
if not key:
|
| 97 |
+
raise ValueError("The key used for updating can not be None or empty")
|
| 98 |
+
if not isinstance(key, str):
|
| 99 |
+
raise TypeError("The key used for updating must be a string.")
|
| 100 |
+
self._key = key
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class AzureSasCredential:
|
| 104 |
+
"""Credential type used for authenticating to an Azure service.
|
| 105 |
+
It provides the ability to update the shared access signature without creating a new client.
|
| 106 |
+
|
| 107 |
+
:param str signature: The shared access signature used to authenticate to an Azure service
|
| 108 |
+
:raises: TypeError
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
def __init__(self, signature: str) -> None:
|
| 112 |
+
if not isinstance(signature, str):
|
| 113 |
+
raise TypeError("signature must be a string.")
|
| 114 |
+
self._signature = signature
|
| 115 |
+
|
| 116 |
+
@property
|
| 117 |
+
def signature(self) -> str:
|
| 118 |
+
"""The value of the configured shared access signature.
|
| 119 |
+
|
| 120 |
+
:rtype: str
|
| 121 |
+
:return: The value of the configured shared access signature.
|
| 122 |
+
"""
|
| 123 |
+
return self._signature
|
| 124 |
+
|
| 125 |
+
def update(self, signature: str) -> None:
|
| 126 |
+
"""Update the shared access signature.
|
| 127 |
+
|
| 128 |
+
This can be used when you've regenerated your shared access signature and want
|
| 129 |
+
to update long-lived clients.
|
| 130 |
+
|
| 131 |
+
:param str signature: The shared access signature used to authenticate to an Azure service
|
| 132 |
+
:raises: ValueError or TypeError
|
| 133 |
+
"""
|
| 134 |
+
if not signature:
|
| 135 |
+
raise ValueError("The signature used for updating can not be None or empty")
|
| 136 |
+
if not isinstance(signature, str):
|
| 137 |
+
raise TypeError("The signature used for updating must be a string.")
|
| 138 |
+
self._signature = signature
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class AzureNamedKeyCredential:
|
| 142 |
+
"""Credential type used for working with any service needing a named key that follows patterns
|
| 143 |
+
established by the other credential types.
|
| 144 |
+
|
| 145 |
+
:param str name: The name of the credential used to authenticate to an Azure service.
|
| 146 |
+
:param str key: The key used to authenticate to an Azure service.
|
| 147 |
+
:raises: TypeError
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def __init__(self, name: str, key: str) -> None:
|
| 151 |
+
if not isinstance(name, str) or not isinstance(key, str):
|
| 152 |
+
raise TypeError("Both name and key must be strings.")
|
| 153 |
+
self._credential = AzureNamedKey(name, key)
|
| 154 |
+
|
| 155 |
+
@property
|
| 156 |
+
def named_key(self) -> AzureNamedKey:
|
| 157 |
+
"""The value of the configured name.
|
| 158 |
+
|
| 159 |
+
:rtype: AzureNamedKey
|
| 160 |
+
:return: The value of the configured name.
|
| 161 |
+
"""
|
| 162 |
+
return self._credential
|
| 163 |
+
|
| 164 |
+
def update(self, name: str, key: str) -> None:
|
| 165 |
+
"""Update the named key credential.
|
| 166 |
+
|
| 167 |
+
Both name and key must be provided in order to update the named key credential.
|
| 168 |
+
Individual attributes cannot be updated.
|
| 169 |
+
|
| 170 |
+
:param str name: The name of the credential used to authenticate to an Azure service.
|
| 171 |
+
:param str key: The key used to authenticate to an Azure service.
|
| 172 |
+
"""
|
| 173 |
+
if not isinstance(name, str) or not isinstance(key, str):
|
| 174 |
+
raise TypeError("Both name and key must be strings.")
|
| 175 |
+
self._credential = AzureNamedKey(name, key)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/credentials_async.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
from typing import Any, Optional, AsyncContextManager, Type
|
| 8 |
+
from typing_extensions import Protocol, runtime_checkable
|
| 9 |
+
from .credentials import AccessToken as _AccessToken
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@runtime_checkable
|
| 13 |
+
class AsyncTokenCredential(Protocol, AsyncContextManager["AsyncTokenCredential"]):
|
| 14 |
+
"""Protocol for classes able to provide OAuth tokens."""
|
| 15 |
+
|
| 16 |
+
async def get_token(
|
| 17 |
+
self,
|
| 18 |
+
*scopes: str,
|
| 19 |
+
claims: Optional[str] = None,
|
| 20 |
+
tenant_id: Optional[str] = None,
|
| 21 |
+
enable_cae: bool = False,
|
| 22 |
+
**kwargs: Any,
|
| 23 |
+
) -> _AccessToken:
|
| 24 |
+
"""Request an access token for `scopes`.
|
| 25 |
+
|
| 26 |
+
:param str scopes: The type of access needed.
|
| 27 |
+
|
| 28 |
+
:keyword str claims: Additional claims required in the token, such as those returned in a resource
|
| 29 |
+
provider's claims challenge following an authorization failure.
|
| 30 |
+
:keyword str tenant_id: Optional tenant to include in the token request.
|
| 31 |
+
:keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) for the requested
|
| 32 |
+
token. Defaults to False.
|
| 33 |
+
|
| 34 |
+
:rtype: AccessToken
|
| 35 |
+
:return: An AccessToken instance containing the token string and its expiration time in Unix time.
|
| 36 |
+
"""
|
| 37 |
+
...
|
| 38 |
+
|
| 39 |
+
async def close(self) -> None:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
async def __aexit__(
|
| 43 |
+
self,
|
| 44 |
+
exc_type: Optional[Type[BaseException]] = None,
|
| 45 |
+
exc_value: Optional[BaseException] = None,
|
| 46 |
+
traceback: Optional[TracebackType] = None,
|
| 47 |
+
) -> None:
|
| 48 |
+
pass
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/exceptions.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
import json
|
| 28 |
+
import logging
|
| 29 |
+
import sys
|
| 30 |
+
|
| 31 |
+
from types import TracebackType
|
| 32 |
+
from typing import (
|
| 33 |
+
Callable,
|
| 34 |
+
Any,
|
| 35 |
+
Optional,
|
| 36 |
+
Union,
|
| 37 |
+
Type,
|
| 38 |
+
List,
|
| 39 |
+
Mapping,
|
| 40 |
+
TypeVar,
|
| 41 |
+
Generic,
|
| 42 |
+
Dict,
|
| 43 |
+
NoReturn,
|
| 44 |
+
TYPE_CHECKING,
|
| 45 |
+
)
|
| 46 |
+
from typing_extensions import Protocol, runtime_checkable
|
| 47 |
+
|
| 48 |
+
_LOGGER = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
if TYPE_CHECKING:
|
| 51 |
+
from azure.core.pipeline.policies import RequestHistory
|
| 52 |
+
|
| 53 |
+
HTTPResponseType = TypeVar("HTTPResponseType")
|
| 54 |
+
HTTPRequestType = TypeVar("HTTPRequestType")
|
| 55 |
+
KeyType = TypeVar("KeyType")
|
| 56 |
+
ValueType = TypeVar("ValueType")
|
| 57 |
+
# To replace when typing.Self is available in our baseline
|
| 58 |
+
SelfODataV4Format = TypeVar("SelfODataV4Format", bound="ODataV4Format")
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
__all__ = [
|
| 62 |
+
"AzureError",
|
| 63 |
+
"ServiceRequestError",
|
| 64 |
+
"ServiceResponseError",
|
| 65 |
+
"HttpResponseError",
|
| 66 |
+
"DecodeError",
|
| 67 |
+
"ResourceExistsError",
|
| 68 |
+
"ResourceNotFoundError",
|
| 69 |
+
"ClientAuthenticationError",
|
| 70 |
+
"ResourceModifiedError",
|
| 71 |
+
"ResourceNotModifiedError",
|
| 72 |
+
"TooManyRedirectsError",
|
| 73 |
+
"ODataV4Format",
|
| 74 |
+
"ODataV4Error",
|
| 75 |
+
"StreamConsumedError",
|
| 76 |
+
"StreamClosedError",
|
| 77 |
+
"ResponseNotReadError",
|
| 78 |
+
"SerializationError",
|
| 79 |
+
"DeserializationError",
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def raise_with_traceback(exception: Callable, *args: Any, message: str = "", **kwargs: Any) -> NoReturn:
|
| 84 |
+
"""Raise exception with a specified traceback.
|
| 85 |
+
This MUST be called inside a "except" clause.
|
| 86 |
+
|
| 87 |
+
.. note:: This method is deprecated since we don't support Python 2 anymore. Use raise/from instead.
|
| 88 |
+
|
| 89 |
+
:param Exception exception: Error type to be raised.
|
| 90 |
+
:param any args: Any additional args to be included with exception.
|
| 91 |
+
:keyword str message: Message to be associated with the exception. If omitted, defaults to an empty string.
|
| 92 |
+
"""
|
| 93 |
+
exc_type, exc_value, exc_traceback = sys.exc_info()
|
| 94 |
+
# If not called inside an "except", exc_type will be None. Assume it will not happen
|
| 95 |
+
if exc_type is None:
|
| 96 |
+
raise ValueError("raise_with_traceback can only be used in except clauses")
|
| 97 |
+
exc_msg = "{}, {}: {}".format(message, exc_type.__name__, exc_value)
|
| 98 |
+
error = exception(exc_msg, *args, **kwargs)
|
| 99 |
+
try:
|
| 100 |
+
raise error.with_traceback(exc_traceback) # pylint: disable=raise-missing-from
|
| 101 |
+
except AttributeError: # Python 2
|
| 102 |
+
error.__traceback__ = exc_traceback
|
| 103 |
+
raise error # pylint: disable=raise-missing-from
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@runtime_checkable
|
| 107 |
+
class _HttpResponseCommonAPI(Protocol):
|
| 108 |
+
"""Protocol used by exceptions for HTTP response.
|
| 109 |
+
|
| 110 |
+
As HttpResponseError uses very few properties of HttpResponse, a protocol
|
| 111 |
+
is faster and simpler than import all the possible types (at least 6).
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def reason(self) -> Optional[str]:
|
| 116 |
+
...
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def status_code(self) -> Optional[int]:
|
| 120 |
+
...
|
| 121 |
+
|
| 122 |
+
def text(self) -> str:
|
| 123 |
+
...
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def request(self) -> object: # object as type, since all we need is str() on it
|
| 127 |
+
...
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class ErrorMap(Generic[KeyType, ValueType]):
|
| 131 |
+
"""Error Map class. To be used in map_error method, behaves like a dictionary.
|
| 132 |
+
It returns the error type if it is found in custom_error_map. Or return default_error
|
| 133 |
+
|
| 134 |
+
:param dict custom_error_map: User-defined error map, it is used to map status codes to error types.
|
| 135 |
+
:keyword error default_error: Default error type. It is returned if the status code is not found in custom_error_map
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
def __init__(
|
| 139 |
+
self, # pylint: disable=unused-argument
|
| 140 |
+
custom_error_map: Optional[Mapping[KeyType, ValueType]] = None,
|
| 141 |
+
*,
|
| 142 |
+
default_error: Optional[ValueType] = None,
|
| 143 |
+
**kwargs: Any,
|
| 144 |
+
) -> None:
|
| 145 |
+
self._custom_error_map = custom_error_map or {}
|
| 146 |
+
self._default_error = default_error
|
| 147 |
+
|
| 148 |
+
def get(self, key: KeyType) -> Optional[ValueType]:
|
| 149 |
+
ret = self._custom_error_map.get(key)
|
| 150 |
+
if ret:
|
| 151 |
+
return ret
|
| 152 |
+
return self._default_error
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def map_error(
|
| 156 |
+
status_code: int, response: _HttpResponseCommonAPI, error_map: Mapping[int, Type[HttpResponseError]]
|
| 157 |
+
) -> None:
|
| 158 |
+
if not error_map:
|
| 159 |
+
return
|
| 160 |
+
error_type = error_map.get(status_code)
|
| 161 |
+
if not error_type:
|
| 162 |
+
return
|
| 163 |
+
error = error_type(response=response)
|
| 164 |
+
raise error
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class ODataV4Format:
|
| 168 |
+
"""Class to describe OData V4 error format.
|
| 169 |
+
|
| 170 |
+
http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091
|
| 171 |
+
|
| 172 |
+
Example of JSON:
|
| 173 |
+
|
| 174 |
+
.. code-block:: json
|
| 175 |
+
|
| 176 |
+
{
|
| 177 |
+
"error": {
|
| 178 |
+
"code": "ValidationError",
|
| 179 |
+
"message": "One or more fields contain incorrect values: ",
|
| 180 |
+
"details": [
|
| 181 |
+
{
|
| 182 |
+
"code": "ValidationError",
|
| 183 |
+
"target": "representation",
|
| 184 |
+
"message": "Parsing error(s): String '' does not match regex pattern '^[^{}/ :]+(?: :\\\\d+)?$'.
|
| 185 |
+
Path 'host', line 1, position 297."
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"code": "ValidationError",
|
| 189 |
+
"target": "representation",
|
| 190 |
+
"message": "Parsing error(s): The input OpenAPI file is not valid for the OpenAPI specificate
|
| 191 |
+
https: //github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md
|
| 192 |
+
(schema https://github.com/OAI/OpenAPI-Specification/blob/master/schemas/v2.0/schema.json)."
|
| 193 |
+
}
|
| 194 |
+
]
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
:param dict json_object: A Python dict representing a ODataV4 JSON
|
| 199 |
+
:ivar str ~.code: Its value is a service-defined error code.
|
| 200 |
+
This code serves as a sub-status for the HTTP error code specified in the response.
|
| 201 |
+
:ivar str message: Human-readable, language-dependent representation of the error.
|
| 202 |
+
:ivar str target: The target of the particular error (for example, the name of the property in error).
|
| 203 |
+
This field is optional and may be None.
|
| 204 |
+
:ivar list[ODataV4Format] details: Array of ODataV4Format instances that MUST contain name/value pairs
|
| 205 |
+
for code and message, and MAY contain a name/value pair for target, as described above.
|
| 206 |
+
:ivar dict innererror: An object. The contents of this object are service-defined.
|
| 207 |
+
Usually this object contains information that will help debug the service.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
CODE_LABEL = "code"
|
| 211 |
+
MESSAGE_LABEL = "message"
|
| 212 |
+
TARGET_LABEL = "target"
|
| 213 |
+
DETAILS_LABEL = "details"
|
| 214 |
+
INNERERROR_LABEL = "innererror"
|
| 215 |
+
|
| 216 |
+
def __init__(self, json_object: Mapping[str, Any]) -> None:
|
| 217 |
+
if "error" in json_object:
|
| 218 |
+
json_object = json_object["error"]
|
| 219 |
+
cls: Type[ODataV4Format] = self.__class__
|
| 220 |
+
|
| 221 |
+
# Required fields, but assume they could be missing still to be robust
|
| 222 |
+
self.code: Optional[str] = json_object.get(cls.CODE_LABEL)
|
| 223 |
+
self.message: Optional[str] = json_object.get(cls.MESSAGE_LABEL)
|
| 224 |
+
|
| 225 |
+
if not (self.code or self.message):
|
| 226 |
+
raise ValueError("Impossible to extract code/message from received JSON:\n" + json.dumps(json_object))
|
| 227 |
+
|
| 228 |
+
# Optional fields
|
| 229 |
+
self.target: Optional[str] = json_object.get(cls.TARGET_LABEL)
|
| 230 |
+
|
| 231 |
+
# details is recursive of this very format
|
| 232 |
+
self.details: List[ODataV4Format] = []
|
| 233 |
+
for detail_node in json_object.get(cls.DETAILS_LABEL) or []:
|
| 234 |
+
try:
|
| 235 |
+
self.details.append(self.__class__(detail_node))
|
| 236 |
+
except Exception: # pylint: disable=broad-except
|
| 237 |
+
pass
|
| 238 |
+
|
| 239 |
+
self.innererror: Mapping[str, Any] = json_object.get(cls.INNERERROR_LABEL, {})
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def error(self: SelfODataV4Format) -> SelfODataV4Format:
|
| 243 |
+
import warnings
|
| 244 |
+
|
| 245 |
+
warnings.warn(
|
| 246 |
+
"error.error from azure exceptions is deprecated, just simply use 'error' once",
|
| 247 |
+
DeprecationWarning,
|
| 248 |
+
)
|
| 249 |
+
return self
|
| 250 |
+
|
| 251 |
+
def __str__(self) -> str:
|
| 252 |
+
return "({}) {}\n{}".format(self.code, self.message, self.message_details())
|
| 253 |
+
|
| 254 |
+
def message_details(self) -> str:
|
| 255 |
+
"""Return a detailed string of the error.
|
| 256 |
+
|
| 257 |
+
:return: A string with the details of the error.
|
| 258 |
+
:rtype: str
|
| 259 |
+
"""
|
| 260 |
+
error_str = "Code: {}".format(self.code)
|
| 261 |
+
error_str += "\nMessage: {}".format(self.message)
|
| 262 |
+
if self.target:
|
| 263 |
+
error_str += "\nTarget: {}".format(self.target)
|
| 264 |
+
|
| 265 |
+
if self.details:
|
| 266 |
+
error_str += "\nException Details:"
|
| 267 |
+
for error_obj in self.details:
|
| 268 |
+
# Indent for visibility
|
| 269 |
+
error_str += "\n".join("\t" + s for s in str(error_obj).splitlines())
|
| 270 |
+
|
| 271 |
+
if self.innererror:
|
| 272 |
+
error_str += "\nInner error: {}".format(json.dumps(self.innererror, indent=4))
|
| 273 |
+
return error_str
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class AzureError(Exception):
|
| 277 |
+
"""Base exception for all errors.
|
| 278 |
+
|
| 279 |
+
:param object message: The message object stringified as 'message' attribute
|
| 280 |
+
:keyword error: The original exception if any
|
| 281 |
+
:paramtype error: Exception
|
| 282 |
+
|
| 283 |
+
:ivar inner_exception: The exception passed with the 'error' kwarg
|
| 284 |
+
:vartype inner_exception: Exception
|
| 285 |
+
:ivar exc_type: The exc_type from sys.exc_info()
|
| 286 |
+
:ivar exc_value: The exc_value from sys.exc_info()
|
| 287 |
+
:ivar exc_traceback: The exc_traceback from sys.exc_info()
|
| 288 |
+
:ivar exc_msg: A string formatting of message parameter, exc_type and exc_value
|
| 289 |
+
:ivar str message: A stringified version of the message parameter
|
| 290 |
+
:ivar str continuation_token: A token reference to continue an incomplete operation. This value is optional
|
| 291 |
+
and will be `None` where continuation is either unavailable or not applicable.
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def __init__(self, message: Optional[object], *args: Any, **kwargs: Any) -> None:
|
| 295 |
+
self.inner_exception: Optional[BaseException] = kwargs.get("error")
|
| 296 |
+
|
| 297 |
+
exc_info = sys.exc_info()
|
| 298 |
+
self.exc_type: Optional[Type[Any]] = exc_info[0]
|
| 299 |
+
self.exc_value: Optional[BaseException] = exc_info[1]
|
| 300 |
+
self.exc_traceback: Optional[TracebackType] = exc_info[2]
|
| 301 |
+
|
| 302 |
+
self.exc_type = self.exc_type if self.exc_type else type(self.inner_exception)
|
| 303 |
+
self.exc_msg: str = "{}, {}: {}".format(message, self.exc_type.__name__, self.exc_value)
|
| 304 |
+
self.message: str = str(message)
|
| 305 |
+
self.continuation_token: Optional[str] = kwargs.get("continuation_token")
|
| 306 |
+
super(AzureError, self).__init__(self.message, *args)
|
| 307 |
+
|
| 308 |
+
def raise_with_traceback(self) -> None:
|
| 309 |
+
"""Raise the exception with the existing traceback.
|
| 310 |
+
|
| 311 |
+
.. deprecated:: 1.22.0
|
| 312 |
+
This method is deprecated as we don't support Python 2 anymore. Use raise/from instead.
|
| 313 |
+
"""
|
| 314 |
+
try:
|
| 315 |
+
raise super(AzureError, self).with_traceback(self.exc_traceback) # pylint: disable=raise-missing-from
|
| 316 |
+
except AttributeError:
|
| 317 |
+
self.__traceback__: Optional[TracebackType] = self.exc_traceback
|
| 318 |
+
raise self # pylint: disable=raise-missing-from
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class ServiceRequestError(AzureError):
|
| 322 |
+
"""An error occurred while attempt to make a request to the service.
|
| 323 |
+
No request was sent.
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class ServiceResponseError(AzureError):
|
| 328 |
+
"""The request was sent, but the client failed to understand the response.
|
| 329 |
+
The connection may have timed out. These errors can be retried for idempotent or
|
| 330 |
+
safe operations"""
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class ServiceRequestTimeoutError(ServiceRequestError):
|
| 334 |
+
"""Error raised when timeout happens"""
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class ServiceResponseTimeoutError(ServiceResponseError):
|
| 338 |
+
"""Error raised when timeout happens"""
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class HttpResponseError(AzureError):
|
| 342 |
+
"""A request was made, and a non-success status code was received from the service.
|
| 343 |
+
|
| 344 |
+
:param object message: The message object stringified as 'message' attribute
|
| 345 |
+
:param response: The response that triggered the exception.
|
| 346 |
+
:type response: ~azure.core.pipeline.transport.HttpResponse or ~azure.core.pipeline.transport.AsyncHttpResponse
|
| 347 |
+
|
| 348 |
+
:ivar reason: The HTTP response reason
|
| 349 |
+
:vartype reason: str
|
| 350 |
+
:ivar status_code: HttpResponse's status code
|
| 351 |
+
:vartype status_code: int
|
| 352 |
+
:ivar response: The response that triggered the exception.
|
| 353 |
+
:vartype response: ~azure.core.pipeline.transport.HttpResponse or ~azure.core.pipeline.transport.AsyncHttpResponse
|
| 354 |
+
:ivar model: The request body/response body model
|
| 355 |
+
:vartype model: ~msrest.serialization.Model
|
| 356 |
+
:ivar error: The formatted error
|
| 357 |
+
:vartype error: ODataV4Format
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
def __init__(
|
| 361 |
+
self, message: Optional[object] = None, response: Optional[_HttpResponseCommonAPI] = None, **kwargs: Any
|
| 362 |
+
) -> None:
|
| 363 |
+
# Don't want to document this one yet.
|
| 364 |
+
error_format = kwargs.get("error_format", ODataV4Format)
|
| 365 |
+
|
| 366 |
+
self.reason: Optional[str] = None
|
| 367 |
+
self.status_code: Optional[int] = None
|
| 368 |
+
self.response: Optional[_HttpResponseCommonAPI] = response
|
| 369 |
+
if response:
|
| 370 |
+
self.reason = response.reason
|
| 371 |
+
self.status_code = response.status_code
|
| 372 |
+
|
| 373 |
+
# old autorest are setting "error" before calling __init__, so it might be there already
|
| 374 |
+
# transferring into self.model
|
| 375 |
+
model: Optional[Any] = kwargs.pop("model", None)
|
| 376 |
+
self.model: Optional[Any]
|
| 377 |
+
if model is not None: # autorest v5
|
| 378 |
+
self.model = model
|
| 379 |
+
else: # autorest azure-core, for KV 1.0, Storage 12.0, etc.
|
| 380 |
+
self.model = getattr(self, "error", None)
|
| 381 |
+
self.error: Optional[ODataV4Format] = self._parse_odata_body(error_format, response)
|
| 382 |
+
|
| 383 |
+
# By priority, message is:
|
| 384 |
+
# - odatav4 message, OR
|
| 385 |
+
# - parameter "message", OR
|
| 386 |
+
# - generic meassage using "reason"
|
| 387 |
+
if self.error:
|
| 388 |
+
message = str(self.error)
|
| 389 |
+
else:
|
| 390 |
+
message = message or "Operation returned an invalid status '{}'".format(self.reason)
|
| 391 |
+
|
| 392 |
+
super(HttpResponseError, self).__init__(message=message, **kwargs)
|
| 393 |
+
|
| 394 |
+
@staticmethod
|
| 395 |
+
def _parse_odata_body(
|
| 396 |
+
error_format: Type[ODataV4Format], response: Optional[_HttpResponseCommonAPI]
|
| 397 |
+
) -> Optional[ODataV4Format]:
|
| 398 |
+
try:
|
| 399 |
+
# https://github.com/python/mypy/issues/14743#issuecomment-1664725053
|
| 400 |
+
odata_json = json.loads(response.text()) # type: ignore
|
| 401 |
+
return error_format(odata_json)
|
| 402 |
+
except Exception: # pylint: disable=broad-except
|
| 403 |
+
# If the body is not JSON valid, just stop now
|
| 404 |
+
pass
|
| 405 |
+
return None
|
| 406 |
+
|
| 407 |
+
def __str__(self) -> str:
|
| 408 |
+
retval = super(HttpResponseError, self).__str__()
|
| 409 |
+
try:
|
| 410 |
+
# https://github.com/python/mypy/issues/14743#issuecomment-1664725053
|
| 411 |
+
body = self.response.text() # type: ignore
|
| 412 |
+
if body and not self.error:
|
| 413 |
+
return "{}\nContent: {}".format(retval, body)[:2048]
|
| 414 |
+
except Exception: # pylint: disable=broad-except
|
| 415 |
+
pass
|
| 416 |
+
return retval
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
class DecodeError(HttpResponseError):
|
| 420 |
+
"""Error raised during response deserialization."""
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
class IncompleteReadError(DecodeError):
|
| 424 |
+
"""Error raised if peer closes the connection before we have received the complete message body."""
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class ResourceExistsError(HttpResponseError):
|
| 428 |
+
"""An error response with status code 4xx.
|
| 429 |
+
This will not be raised directly by the Azure core pipeline."""
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class ResourceNotFoundError(HttpResponseError):
|
| 433 |
+
"""An error response, typically triggered by a 412 response (for update) or 404 (for get/post)"""
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class ClientAuthenticationError(HttpResponseError):
|
| 437 |
+
"""An error response with status code 4xx.
|
| 438 |
+
This will not be raised directly by the Azure core pipeline."""
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
class ResourceModifiedError(HttpResponseError):
|
| 442 |
+
"""An error response with status code 4xx, typically 412 Conflict.
|
| 443 |
+
This will not be raised directly by the Azure core pipeline."""
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class ResourceNotModifiedError(HttpResponseError):
|
| 447 |
+
"""An error response with status code 304.
|
| 448 |
+
This will not be raised directly by the Azure core pipeline."""
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class TooManyRedirectsError(HttpResponseError, Generic[HTTPRequestType, HTTPResponseType]):
|
| 452 |
+
"""Reached the maximum number of redirect attempts.
|
| 453 |
+
|
| 454 |
+
:param history: The history of requests made while trying to fulfill the request.
|
| 455 |
+
:type history: list[~azure.core.pipeline.policies.RequestHistory]
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
def __init__(
|
| 459 |
+
self, history: "List[RequestHistory[HTTPRequestType, HTTPResponseType]]", *args: Any, **kwargs: Any
|
| 460 |
+
) -> None:
|
| 461 |
+
self.history = history
|
| 462 |
+
message = "Reached maximum redirect attempts."
|
| 463 |
+
super(TooManyRedirectsError, self).__init__(message, *args, **kwargs)
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
class ODataV4Error(HttpResponseError):
|
| 467 |
+
"""An HTTP response error where the JSON is decoded as OData V4 error format.
|
| 468 |
+
|
| 469 |
+
http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091
|
| 470 |
+
|
| 471 |
+
:param ~azure.core.rest.HttpResponse response: The response object.
|
| 472 |
+
:ivar dict odata_json: The parsed JSON body as attribute for convenience.
|
| 473 |
+
:ivar str ~.code: Its value is a service-defined error code.
|
| 474 |
+
This code serves as a sub-status for the HTTP error code specified in the response.
|
| 475 |
+
:ivar str message: Human-readable, language-dependent representation of the error.
|
| 476 |
+
:ivar str target: The target of the particular error (for example, the name of the property in error).
|
| 477 |
+
This field is optional and may be None.
|
| 478 |
+
:ivar list[ODataV4Format] details: Array of ODataV4Format instances that MUST contain name/value pairs
|
| 479 |
+
for code and message, and MAY contain a name/value pair for target, as described above.
|
| 480 |
+
:ivar dict innererror: An object. The contents of this object are service-defined.
|
| 481 |
+
Usually this object contains information that will help debug the service.
|
| 482 |
+
"""
|
| 483 |
+
|
| 484 |
+
_ERROR_FORMAT = ODataV4Format
|
| 485 |
+
|
| 486 |
+
def __init__(self, response: _HttpResponseCommonAPI, **kwargs: Any) -> None:
|
| 487 |
+
# Ensure field are declared, whatever can happen afterwards
|
| 488 |
+
self.odata_json: Optional[Dict[str, Any]] = None
|
| 489 |
+
try:
|
| 490 |
+
self.odata_json = json.loads(response.text())
|
| 491 |
+
odata_message = self.odata_json.setdefault("error", {}).get("message")
|
| 492 |
+
except Exception: # pylint: disable=broad-except
|
| 493 |
+
# If the body is not JSON valid, just stop now
|
| 494 |
+
odata_message = None
|
| 495 |
+
|
| 496 |
+
self.code: Optional[str] = None
|
| 497 |
+
message: Optional[str] = kwargs.get("message", odata_message)
|
| 498 |
+
self.target: Optional[str] = None
|
| 499 |
+
self.details: Optional[List[Any]] = []
|
| 500 |
+
self.innererror: Optional[Mapping[str, Any]] = {}
|
| 501 |
+
|
| 502 |
+
if message and "message" not in kwargs:
|
| 503 |
+
kwargs["message"] = message
|
| 504 |
+
|
| 505 |
+
super(ODataV4Error, self).__init__(response=response, **kwargs)
|
| 506 |
+
|
| 507 |
+
self._error_format: Optional[Union[str, ODataV4Format]] = None
|
| 508 |
+
if self.odata_json:
|
| 509 |
+
try:
|
| 510 |
+
error_node = self.odata_json["error"]
|
| 511 |
+
self._error_format = self._ERROR_FORMAT(error_node)
|
| 512 |
+
self.__dict__.update({k: v for k, v in self._error_format.__dict__.items() if v is not None})
|
| 513 |
+
except Exception: # pylint: disable=broad-except
|
| 514 |
+
_LOGGER.info("Received error message was not valid OdataV4 format.")
|
| 515 |
+
self._error_format = "JSON was invalid for format " + str(self._ERROR_FORMAT)
|
| 516 |
+
|
| 517 |
+
def __str__(self) -> str:
|
| 518 |
+
if self._error_format:
|
| 519 |
+
return str(self._error_format)
|
| 520 |
+
return super(ODataV4Error, self).__str__()
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class StreamConsumedError(AzureError):
|
| 524 |
+
"""Error thrown if you try to access the stream of a response once consumed.
|
| 525 |
+
|
| 526 |
+
It is thrown if you try to read / stream an ~azure.core.rest.HttpResponse or
|
| 527 |
+
~azure.core.rest.AsyncHttpResponse once the response's stream has been consumed.
|
| 528 |
+
|
| 529 |
+
:param response: The response that triggered the exception.
|
| 530 |
+
:type response: ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse
|
| 531 |
+
"""
|
| 532 |
+
|
| 533 |
+
def __init__(self, response: _HttpResponseCommonAPI) -> None:
|
| 534 |
+
message = (
|
| 535 |
+
"You are attempting to read or stream the content from request {}. "
|
| 536 |
+
"You have likely already consumed this stream, so it can not be accessed anymore.".format(response.request)
|
| 537 |
+
)
|
| 538 |
+
super(StreamConsumedError, self).__init__(message)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class StreamClosedError(AzureError):
|
| 542 |
+
"""Error thrown if you try to access the stream of a response once closed.
|
| 543 |
+
|
| 544 |
+
It is thrown if you try to read / stream an ~azure.core.rest.HttpResponse or
|
| 545 |
+
~azure.core.rest.AsyncHttpResponse once the response's stream has been closed.
|
| 546 |
+
|
| 547 |
+
:param response: The response that triggered the exception.
|
| 548 |
+
:type response: ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
def __init__(self, response: _HttpResponseCommonAPI) -> None:
|
| 552 |
+
message = (
|
| 553 |
+
"The content for response from request {} can no longer be read or streamed, since the "
|
| 554 |
+
"response has already been closed.".format(response.request)
|
| 555 |
+
)
|
| 556 |
+
super(StreamClosedError, self).__init__(message)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class ResponseNotReadError(AzureError):
|
| 560 |
+
"""Error thrown if you try to access a response's content without reading first.
|
| 561 |
+
|
| 562 |
+
It is thrown if you try to access an ~azure.core.rest.HttpResponse or
|
| 563 |
+
~azure.core.rest.AsyncHttpResponse's content without first reading the response's bytes in first.
|
| 564 |
+
|
| 565 |
+
:param response: The response that triggered the exception.
|
| 566 |
+
:type response: ~azure.core.rest.HttpResponse or ~azure.core.rest.AsyncHttpResponse
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
def __init__(self, response: _HttpResponseCommonAPI) -> None:
|
| 570 |
+
message = (
|
| 571 |
+
"You have not read in the bytes for the response from request {}. "
|
| 572 |
+
"Call .read() on the response first.".format(response.request)
|
| 573 |
+
)
|
| 574 |
+
super(ResponseNotReadError, self).__init__(message)
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class SerializationError(ValueError):
|
| 578 |
+
"""Raised if an error is encountered during serialization."""
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
class DeserializationError(ValueError):
|
| 582 |
+
"""Raised if an error is encountered during deserialization."""
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/messaging.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
import uuid
|
| 9 |
+
from base64 import b64decode
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from typing import cast, Union, Any, Optional, Dict, TypeVar, Generic
|
| 12 |
+
from .utils._utils import _convert_to_isoformat, TZ_UTC
|
| 13 |
+
from .utils._messaging_shared import _get_json_content
|
| 14 |
+
from .serialization import NULL
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = ["CloudEvent"]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
_Unset: Any = object()
|
| 21 |
+
|
| 22 |
+
DataType = TypeVar("DataType")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CloudEvent(Generic[DataType]): # pylint:disable=too-many-instance-attributes
|
| 26 |
+
"""Properties of the CloudEvent 1.0 Schema.
|
| 27 |
+
All required parameters must be populated in order to send to Azure.
|
| 28 |
+
|
| 29 |
+
:param source: Required. Identifies the context in which an event happened. The combination of id and source must
|
| 30 |
+
be unique for each distinct event. If publishing to a domain topic, source must be the domain topic name.
|
| 31 |
+
:type source: str
|
| 32 |
+
:param type: Required. Type of event related to the originating occurrence.
|
| 33 |
+
:type type: str
|
| 34 |
+
:keyword specversion: Optional. The version of the CloudEvent spec. Defaults to "1.0"
|
| 35 |
+
:paramtype specversion: str
|
| 36 |
+
:keyword data: Optional. Event data specific to the event type.
|
| 37 |
+
:paramtype data: object
|
| 38 |
+
:keyword time: Optional. The time (in UTC) the event was generated.
|
| 39 |
+
:paramtype time: ~datetime.datetime
|
| 40 |
+
:keyword dataschema: Optional. Identifies the schema that data adheres to.
|
| 41 |
+
:paramtype dataschema: str
|
| 42 |
+
:keyword datacontenttype: Optional. Content type of data value.
|
| 43 |
+
:paramtype datacontenttype: str
|
| 44 |
+
:keyword subject: Optional. This describes the subject of the event in the context of the event producer
|
| 45 |
+
(identified by source).
|
| 46 |
+
:paramtype subject: str
|
| 47 |
+
:keyword id: Optional. An identifier for the event. The combination of id and source must be
|
| 48 |
+
unique for each distinct event. If not provided, a random UUID will be generated and used.
|
| 49 |
+
:paramtype id: Optional[str]
|
| 50 |
+
:keyword extensions: Optional. A CloudEvent MAY include any number of additional context attributes
|
| 51 |
+
with distinct names represented as key - value pairs. Each extension must be alphanumeric, lower cased
|
| 52 |
+
and must not exceed the length of 20 characters.
|
| 53 |
+
:paramtype extensions: Optional[dict]
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
source: str
|
| 57 |
+
"""Identifies the context in which an event happened. The combination of id and source must
|
| 58 |
+
be unique for each distinct event. If publishing to a domain topic, source must be the domain topic name."""
|
| 59 |
+
|
| 60 |
+
type: str # pylint: disable=redefined-builtin
|
| 61 |
+
"""Type of event related to the originating occurrence."""
|
| 62 |
+
|
| 63 |
+
specversion: str = "1.0"
|
| 64 |
+
"""The version of the CloudEvent spec. Defaults to "1.0" """
|
| 65 |
+
|
| 66 |
+
id: str # pylint: disable=redefined-builtin
|
| 67 |
+
"""An identifier for the event. The combination of id and source must be
|
| 68 |
+
unique for each distinct event. If not provided, a random UUID will be generated and used."""
|
| 69 |
+
|
| 70 |
+
data: Optional[DataType]
|
| 71 |
+
"""Event data specific to the event type."""
|
| 72 |
+
|
| 73 |
+
time: Optional[datetime]
|
| 74 |
+
"""The time (in UTC) the event was generated."""
|
| 75 |
+
|
| 76 |
+
dataschema: Optional[str]
|
| 77 |
+
"""Identifies the schema that data adheres to."""
|
| 78 |
+
|
| 79 |
+
datacontenttype: Optional[str]
|
| 80 |
+
"""Content type of data value."""
|
| 81 |
+
|
| 82 |
+
subject: Optional[str]
|
| 83 |
+
"""This describes the subject of the event in the context of the event producer
|
| 84 |
+
(identified by source)"""
|
| 85 |
+
|
| 86 |
+
extensions: Optional[Dict[str, Any]]
|
| 87 |
+
"""A CloudEvent MAY include any number of additional context attributes
|
| 88 |
+
with distinct names represented as key - value pairs. Each extension must be alphanumeric, lower cased
|
| 89 |
+
and must not exceed the length of 20 characters."""
|
| 90 |
+
|
| 91 |
+
def __init__(
|
| 92 |
+
self,
|
| 93 |
+
source: str,
|
| 94 |
+
type: str, # pylint: disable=redefined-builtin
|
| 95 |
+
*,
|
| 96 |
+
specversion: Optional[str] = None,
|
| 97 |
+
id: Optional[str] = None, # pylint: disable=redefined-builtin
|
| 98 |
+
time: Optional[datetime] = _Unset,
|
| 99 |
+
datacontenttype: Optional[str] = None,
|
| 100 |
+
dataschema: Optional[str] = None,
|
| 101 |
+
subject: Optional[str] = None,
|
| 102 |
+
data: Optional[DataType] = None,
|
| 103 |
+
extensions: Optional[Dict[str, Any]] = None,
|
| 104 |
+
**kwargs: Any,
|
| 105 |
+
) -> None:
|
| 106 |
+
self.source: str = source
|
| 107 |
+
self.type: str = type
|
| 108 |
+
|
| 109 |
+
if specversion:
|
| 110 |
+
self.specversion: str = specversion
|
| 111 |
+
self.id: str = id if id else str(uuid.uuid4())
|
| 112 |
+
|
| 113 |
+
self.time: Optional[datetime]
|
| 114 |
+
if time is _Unset:
|
| 115 |
+
self.time = datetime.now(TZ_UTC)
|
| 116 |
+
else:
|
| 117 |
+
self.time = time
|
| 118 |
+
|
| 119 |
+
self.datacontenttype: Optional[str] = datacontenttype
|
| 120 |
+
self.dataschema: Optional[str] = dataschema
|
| 121 |
+
self.subject: Optional[str] = subject
|
| 122 |
+
self.data: Optional[DataType] = data
|
| 123 |
+
|
| 124 |
+
self.extensions: Optional[Dict[str, Any]] = extensions
|
| 125 |
+
if self.extensions:
|
| 126 |
+
for key in self.extensions.keys():
|
| 127 |
+
if not key.islower() or not key.isalnum():
|
| 128 |
+
raise ValueError("Extension attributes should be lower cased and alphanumeric.")
|
| 129 |
+
|
| 130 |
+
if kwargs:
|
| 131 |
+
remaining = ", ".join(kwargs.keys())
|
| 132 |
+
raise ValueError(
|
| 133 |
+
f"Unexpected keyword arguments {remaining}. "
|
| 134 |
+
+ "Any extension attributes must be passed explicitly using extensions."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def __repr__(self) -> str:
|
| 138 |
+
return "CloudEvent(source={}, type={}, specversion={}, id={}, time={})".format(
|
| 139 |
+
self.source, self.type, self.specversion, self.id, self.time
|
| 140 |
+
)[:1024]
|
| 141 |
+
|
| 142 |
+
@classmethod
|
| 143 |
+
def from_dict(cls, event: Dict[str, Any]) -> CloudEvent[DataType]:
|
| 144 |
+
"""Returns the deserialized CloudEvent object when a dict is provided.
|
| 145 |
+
|
| 146 |
+
:param event: The dict representation of the event which needs to be deserialized.
|
| 147 |
+
:type event: dict
|
| 148 |
+
:rtype: CloudEvent
|
| 149 |
+
:return: The deserialized CloudEvent object.
|
| 150 |
+
"""
|
| 151 |
+
kwargs: Dict[str, Any] = {}
|
| 152 |
+
reserved_attr = [
|
| 153 |
+
"data",
|
| 154 |
+
"data_base64",
|
| 155 |
+
"id",
|
| 156 |
+
"source",
|
| 157 |
+
"type",
|
| 158 |
+
"specversion",
|
| 159 |
+
"time",
|
| 160 |
+
"dataschema",
|
| 161 |
+
"datacontenttype",
|
| 162 |
+
"subject",
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
if "data" in event and "data_base64" in event:
|
| 166 |
+
raise ValueError("Invalid input. Only one of data and data_base64 must be present.")
|
| 167 |
+
|
| 168 |
+
if "data" in event:
|
| 169 |
+
data = event.get("data")
|
| 170 |
+
kwargs["data"] = data if data is not None else NULL
|
| 171 |
+
elif "data_base64" in event:
|
| 172 |
+
kwargs["data"] = b64decode(cast(Union[str, bytes], event.get("data_base64")))
|
| 173 |
+
|
| 174 |
+
for item in ["datacontenttype", "dataschema", "subject"]:
|
| 175 |
+
if item in event:
|
| 176 |
+
val = event.get(item)
|
| 177 |
+
kwargs[item] = val if val is not None else NULL
|
| 178 |
+
|
| 179 |
+
extensions = {k: v for k, v in event.items() if k not in reserved_attr}
|
| 180 |
+
if extensions:
|
| 181 |
+
kwargs["extensions"] = extensions
|
| 182 |
+
|
| 183 |
+
try:
|
| 184 |
+
event_obj = cls(
|
| 185 |
+
id=event.get("id"),
|
| 186 |
+
source=event["source"],
|
| 187 |
+
type=event["type"],
|
| 188 |
+
specversion=event.get("specversion"),
|
| 189 |
+
time=_convert_to_isoformat(event.get("time")),
|
| 190 |
+
**kwargs,
|
| 191 |
+
)
|
| 192 |
+
except KeyError as err:
|
| 193 |
+
# https://github.com/cloudevents/spec Cloud event spec requires source, type,
|
| 194 |
+
# specversion. We autopopulate everything other than source, type.
|
| 195 |
+
# So we will assume the KeyError is coming from source/type access.
|
| 196 |
+
if all(
|
| 197 |
+
key in event
|
| 198 |
+
for key in (
|
| 199 |
+
"subject",
|
| 200 |
+
"eventType",
|
| 201 |
+
"data",
|
| 202 |
+
"dataVersion",
|
| 203 |
+
"id",
|
| 204 |
+
"eventTime",
|
| 205 |
+
)
|
| 206 |
+
):
|
| 207 |
+
raise ValueError(
|
| 208 |
+
"The event you are trying to parse follows the Eventgrid Schema. You can parse"
|
| 209 |
+
+ " EventGrid events using EventGridEvent.from_dict method in the azure-eventgrid library."
|
| 210 |
+
) from err
|
| 211 |
+
raise ValueError(
|
| 212 |
+
"The event does not conform to the cloud event spec https://github.com/cloudevents/spec."
|
| 213 |
+
+ " The `source` and `type` params are required."
|
| 214 |
+
) from err
|
| 215 |
+
return event_obj
|
| 216 |
+
|
| 217 |
+
@classmethod
|
| 218 |
+
def from_json(cls, event: Any) -> CloudEvent[DataType]:
|
| 219 |
+
"""Returns the deserialized CloudEvent object when a json payload is provided.
|
| 220 |
+
|
| 221 |
+
:param event: The json string that should be converted into a CloudEvent. This can also be
|
| 222 |
+
a storage QueueMessage, eventhub's EventData or ServiceBusMessage
|
| 223 |
+
:type event: object
|
| 224 |
+
:rtype: CloudEvent
|
| 225 |
+
:return: The deserialized CloudEvent object.
|
| 226 |
+
:raises ValueError: If the provided JSON is invalid.
|
| 227 |
+
"""
|
| 228 |
+
dict_event = _get_json_content(event)
|
| 229 |
+
return CloudEvent.from_dict(dict_event)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/paging.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
import itertools
|
| 27 |
+
from typing import ( # pylint: disable=unused-import
|
| 28 |
+
Callable,
|
| 29 |
+
Optional,
|
| 30 |
+
TypeVar,
|
| 31 |
+
Iterator,
|
| 32 |
+
Iterable,
|
| 33 |
+
Tuple,
|
| 34 |
+
Any,
|
| 35 |
+
)
|
| 36 |
+
import logging
|
| 37 |
+
|
| 38 |
+
from .exceptions import AzureError
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
_LOGGER = logging.getLogger(__name__)
|
| 42 |
+
|
| 43 |
+
ReturnType = TypeVar("ReturnType")
|
| 44 |
+
ResponseType = TypeVar("ResponseType")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class PageIterator(Iterator[Iterator[ReturnType]]):
|
| 48 |
+
def __init__(
|
| 49 |
+
self,
|
| 50 |
+
get_next: Callable[[Optional[str]], ResponseType],
|
| 51 |
+
extract_data: Callable[[ResponseType], Tuple[str, Iterable[ReturnType]]],
|
| 52 |
+
continuation_token: Optional[str] = None,
|
| 53 |
+
):
|
| 54 |
+
"""Return an iterator of pages.
|
| 55 |
+
|
| 56 |
+
:param get_next: Callable that take the continuation token and return a HTTP response
|
| 57 |
+
:param extract_data: Callable that take an HTTP response and return a tuple continuation token,
|
| 58 |
+
list of ReturnType
|
| 59 |
+
:param str continuation_token: The continuation token needed by get_next
|
| 60 |
+
"""
|
| 61 |
+
self._get_next = get_next
|
| 62 |
+
self._extract_data = extract_data
|
| 63 |
+
self.continuation_token = continuation_token
|
| 64 |
+
self._did_a_call_already = False
|
| 65 |
+
self._response: Optional[ResponseType] = None
|
| 66 |
+
self._current_page: Optional[Iterable[ReturnType]] = None
|
| 67 |
+
|
| 68 |
+
def __iter__(self) -> Iterator[Iterator[ReturnType]]:
|
| 69 |
+
return self
|
| 70 |
+
|
| 71 |
+
def __next__(self) -> Iterator[ReturnType]:
|
| 72 |
+
if self.continuation_token is None and self._did_a_call_already:
|
| 73 |
+
raise StopIteration("End of paging")
|
| 74 |
+
try:
|
| 75 |
+
self._response = self._get_next(self.continuation_token)
|
| 76 |
+
except AzureError as error:
|
| 77 |
+
if not error.continuation_token:
|
| 78 |
+
error.continuation_token = self.continuation_token
|
| 79 |
+
raise
|
| 80 |
+
|
| 81 |
+
self._did_a_call_already = True
|
| 82 |
+
|
| 83 |
+
self.continuation_token, self._current_page = self._extract_data(self._response)
|
| 84 |
+
|
| 85 |
+
return iter(self._current_page)
|
| 86 |
+
|
| 87 |
+
next = __next__ # Python 2 compatibility. Can't be removed as some people are using ".next()" even in Py3
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class ItemPaged(Iterator[ReturnType]):
|
| 91 |
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
| 92 |
+
"""Return an iterator of items.
|
| 93 |
+
|
| 94 |
+
args and kwargs will be passed to the PageIterator constructor directly,
|
| 95 |
+
except page_iterator_class
|
| 96 |
+
"""
|
| 97 |
+
self._args = args
|
| 98 |
+
self._kwargs = kwargs
|
| 99 |
+
self._page_iterator: Optional[Iterator[ReturnType]] = None
|
| 100 |
+
self._page_iterator_class = self._kwargs.pop("page_iterator_class", PageIterator)
|
| 101 |
+
|
| 102 |
+
def by_page(self, continuation_token: Optional[str] = None) -> Iterator[Iterator[ReturnType]]:
|
| 103 |
+
"""Get an iterator of pages of objects, instead of an iterator of objects.
|
| 104 |
+
|
| 105 |
+
:param str continuation_token:
|
| 106 |
+
An opaque continuation token. This value can be retrieved from the
|
| 107 |
+
continuation_token field of a previous generator object. If specified,
|
| 108 |
+
this generator will begin returning results from this point.
|
| 109 |
+
:returns: An iterator of pages (themselves iterator of objects)
|
| 110 |
+
:rtype: iterator[iterator[ReturnType]]
|
| 111 |
+
"""
|
| 112 |
+
return self._page_iterator_class(continuation_token=continuation_token, *self._args, **self._kwargs)
|
| 113 |
+
|
| 114 |
+
def __repr__(self) -> str:
|
| 115 |
+
return "<iterator object azure.core.paging.ItemPaged at {}>".format(hex(id(self)))
|
| 116 |
+
|
| 117 |
+
def __iter__(self) -> Iterator[ReturnType]:
|
| 118 |
+
return self
|
| 119 |
+
|
| 120 |
+
def __next__(self) -> ReturnType:
|
| 121 |
+
if self._page_iterator is None:
|
| 122 |
+
self._page_iterator = itertools.chain.from_iterable(self.by_page())
|
| 123 |
+
return next(self._page_iterator)
|
| 124 |
+
|
| 125 |
+
next = __next__ # Python 2 compatibility. Can't be removed as some people are using ".next()" even in Py3
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/py.typed
ADDED
|
File without changes
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/serialization.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
import base64
|
| 8 |
+
from json import JSONEncoder
|
| 9 |
+
from typing import Union, cast, Any
|
| 10 |
+
from datetime import datetime, date, time, timedelta
|
| 11 |
+
from datetime import timezone
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ["NULL", "AzureJSONEncoder"]
|
| 15 |
+
TZ_UTC = timezone.utc
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _Null:
|
| 19 |
+
"""To create a Falsy object"""
|
| 20 |
+
|
| 21 |
+
def __bool__(self) -> bool:
|
| 22 |
+
return False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
NULL = _Null()
|
| 26 |
+
"""
|
| 27 |
+
A falsy sentinel object which is supposed to be used to specify attributes
|
| 28 |
+
with no data. This gets serialized to `null` on the wire.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _timedelta_as_isostr(td: timedelta) -> str:
|
| 33 |
+
"""Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S'
|
| 34 |
+
|
| 35 |
+
Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython
|
| 36 |
+
|
| 37 |
+
:param td: The timedelta object to convert
|
| 38 |
+
:type td: datetime.timedelta
|
| 39 |
+
:return: An ISO 8601 formatted string representing the timedelta object
|
| 40 |
+
:rtype: str
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
# Split seconds to larger units
|
| 44 |
+
seconds = td.total_seconds()
|
| 45 |
+
minutes, seconds = divmod(seconds, 60)
|
| 46 |
+
hours, minutes = divmod(minutes, 60)
|
| 47 |
+
days, hours = divmod(hours, 24)
|
| 48 |
+
|
| 49 |
+
days, hours, minutes = list(map(int, (days, hours, minutes)))
|
| 50 |
+
seconds = round(seconds, 6)
|
| 51 |
+
|
| 52 |
+
# Build date
|
| 53 |
+
date_str = ""
|
| 54 |
+
if days:
|
| 55 |
+
date_str = "%sD" % days
|
| 56 |
+
|
| 57 |
+
# Build time
|
| 58 |
+
time_str = "T"
|
| 59 |
+
|
| 60 |
+
# Hours
|
| 61 |
+
bigger_exists = date_str or hours
|
| 62 |
+
if bigger_exists:
|
| 63 |
+
time_str += "{:02}H".format(hours)
|
| 64 |
+
|
| 65 |
+
# Minutes
|
| 66 |
+
bigger_exists = bigger_exists or minutes
|
| 67 |
+
if bigger_exists:
|
| 68 |
+
time_str += "{:02}M".format(minutes)
|
| 69 |
+
|
| 70 |
+
# Seconds
|
| 71 |
+
try:
|
| 72 |
+
if seconds.is_integer():
|
| 73 |
+
seconds_string = "{:02}".format(int(seconds))
|
| 74 |
+
else:
|
| 75 |
+
# 9 chars long w/ leading 0, 6 digits after decimal
|
| 76 |
+
seconds_string = "%09.6f" % seconds
|
| 77 |
+
# Remove trailing zeros
|
| 78 |
+
seconds_string = seconds_string.rstrip("0")
|
| 79 |
+
except AttributeError: # int.is_integer() raises
|
| 80 |
+
seconds_string = "{:02}".format(seconds)
|
| 81 |
+
|
| 82 |
+
time_str += "{}S".format(seconds_string)
|
| 83 |
+
|
| 84 |
+
return "P" + date_str + time_str
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _datetime_as_isostr(dt: Union[datetime, date, time, timedelta]) -> str:
|
| 88 |
+
"""Converts a datetime.(datetime|date|time|timedelta) object into an ISO 8601 formatted string.
|
| 89 |
+
|
| 90 |
+
:param dt: The datetime object to convert
|
| 91 |
+
:type dt: datetime.datetime or datetime.date or datetime.time or datetime.timedelta
|
| 92 |
+
:return: An ISO 8601 formatted string representing the datetime object
|
| 93 |
+
:rtype: str
|
| 94 |
+
"""
|
| 95 |
+
# First try datetime.datetime
|
| 96 |
+
if hasattr(dt, "year") and hasattr(dt, "hour"):
|
| 97 |
+
dt = cast(datetime, dt)
|
| 98 |
+
# astimezone() fails for naive times in Python 2.7, so make make sure dt is aware (tzinfo is set)
|
| 99 |
+
if not dt.tzinfo:
|
| 100 |
+
iso_formatted = dt.replace(tzinfo=TZ_UTC).isoformat()
|
| 101 |
+
else:
|
| 102 |
+
iso_formatted = dt.astimezone(TZ_UTC).isoformat()
|
| 103 |
+
# Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt)
|
| 104 |
+
return iso_formatted.replace("+00:00", "Z")
|
| 105 |
+
# Next try datetime.date or datetime.time
|
| 106 |
+
try:
|
| 107 |
+
dt = cast(Union[date, time], dt)
|
| 108 |
+
return dt.isoformat()
|
| 109 |
+
# Last, try datetime.timedelta
|
| 110 |
+
except AttributeError:
|
| 111 |
+
dt = cast(timedelta, dt)
|
| 112 |
+
return _timedelta_as_isostr(dt)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class AzureJSONEncoder(JSONEncoder):
|
| 116 |
+
"""A JSON encoder that's capable of serializing datetime objects and bytes."""
|
| 117 |
+
|
| 118 |
+
def default(self, o: Any) -> Any: # pylint: disable=too-many-return-statements
|
| 119 |
+
if isinstance(o, (bytes, bytearray)):
|
| 120 |
+
return base64.b64encode(o).decode()
|
| 121 |
+
try:
|
| 122 |
+
return _datetime_as_isostr(o)
|
| 123 |
+
except AttributeError:
|
| 124 |
+
pass
|
| 125 |
+
return super(AzureJSONEncoder, self).default(o)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/core/settings.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to deal
|
| 9 |
+
# in the Software without restriction, including without limitation the rights
|
| 10 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 11 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 22 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 23 |
+
# THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
"""Provide access to settings for globally used Azure configuration values.
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import annotations
|
| 29 |
+
from collections import namedtuple
|
| 30 |
+
from enum import Enum
|
| 31 |
+
import logging
|
| 32 |
+
import os
|
| 33 |
+
import sys
|
| 34 |
+
from typing import Type, Optional, Callable, Union, Dict, Any, TypeVar, Tuple, Generic, Mapping, List
|
| 35 |
+
from azure.core.tracing import AbstractSpan
|
| 36 |
+
|
| 37 |
+
ValidInputType = TypeVar("ValidInputType")
|
| 38 |
+
ValueType = TypeVar("ValueType")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
__all__ = ("settings", "Settings")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
|
| 45 |
+
class _Unset(Enum):
|
| 46 |
+
token = 0
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_unset = _Unset.token
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def convert_bool(value: Union[str, bool]) -> bool:
|
| 53 |
+
"""Convert a string to True or False
|
| 54 |
+
|
| 55 |
+
If a boolean is passed in, it is returned as-is. Otherwise the function
|
| 56 |
+
maps the following strings, ignoring case:
|
| 57 |
+
|
| 58 |
+
* "yes", "1", "on" -> True
|
| 59 |
+
" "no", "0", "off" -> False
|
| 60 |
+
|
| 61 |
+
:param value: the value to convert
|
| 62 |
+
:type value: str or bool
|
| 63 |
+
:returns: A boolean value matching the intent of the input
|
| 64 |
+
:rtype: bool
|
| 65 |
+
:raises ValueError: If conversion to bool fails
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
if isinstance(value, bool):
|
| 69 |
+
return value
|
| 70 |
+
val = value.lower()
|
| 71 |
+
if val in ["yes", "1", "on", "true", "True"]:
|
| 72 |
+
return True
|
| 73 |
+
if val in ["no", "0", "off", "false", "False"]:
|
| 74 |
+
return False
|
| 75 |
+
raise ValueError("Cannot convert {} to boolean value".format(value))
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
_levels = {
|
| 79 |
+
"CRITICAL": logging.CRITICAL,
|
| 80 |
+
"ERROR": logging.ERROR,
|
| 81 |
+
"WARNING": logging.WARNING,
|
| 82 |
+
"INFO": logging.INFO,
|
| 83 |
+
"DEBUG": logging.DEBUG,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def convert_logging(value: Union[str, int]) -> int:
|
| 88 |
+
"""Convert a string to a Python logging level
|
| 89 |
+
|
| 90 |
+
If a log level is passed in, it is returned as-is. Otherwise the function
|
| 91 |
+
understands the following strings, ignoring case:
|
| 92 |
+
|
| 93 |
+
* "critical"
|
| 94 |
+
* "error"
|
| 95 |
+
* "warning"
|
| 96 |
+
* "info"
|
| 97 |
+
* "debug"
|
| 98 |
+
|
| 99 |
+
:param value: the value to convert
|
| 100 |
+
:type value: str or int
|
| 101 |
+
:returns: A log level as an int. See the logging module for details.
|
| 102 |
+
:rtype: int
|
| 103 |
+
:raises ValueError: If conversion to log level fails
|
| 104 |
+
|
| 105 |
+
"""
|
| 106 |
+
if isinstance(value, int):
|
| 107 |
+
# If it's an int, return it. We don't need to check if it's in _levels, as custom int levels are allowed.
|
| 108 |
+
# https://docs.python.org/3/library/logging.html#levels
|
| 109 |
+
return value
|
| 110 |
+
val = value.upper()
|
| 111 |
+
level = _levels.get(val)
|
| 112 |
+
if not level:
|
| 113 |
+
raise ValueError("Cannot convert {} to log level, valid values are: {}".format(value, ", ".join(_levels)))
|
| 114 |
+
return level
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _get_opencensus_span() -> Optional[Type[AbstractSpan]]:
|
| 118 |
+
"""Returns the OpenCensusSpan if the opencensus tracing plugin is installed else returns None.
|
| 119 |
+
|
| 120 |
+
:rtype: type[AbstractSpan] or None
|
| 121 |
+
:returns: OpenCensusSpan type or None
|
| 122 |
+
"""
|
| 123 |
+
try:
|
| 124 |
+
from azure.core.tracing.ext.opencensus_span import ( # pylint:disable=redefined-outer-name
|
| 125 |
+
OpenCensusSpan,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
return OpenCensusSpan
|
| 129 |
+
except ImportError:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _get_opentelemetry_span() -> Optional[Type[AbstractSpan]]:
|
| 134 |
+
"""Returns the OpenTelemetrySpan if the opentelemetry tracing plugin is installed else returns None.
|
| 135 |
+
|
| 136 |
+
:rtype: type[AbstractSpan] or None
|
| 137 |
+
:returns: OpenTelemetrySpan type or None
|
| 138 |
+
"""
|
| 139 |
+
try:
|
| 140 |
+
from azure.core.tracing.ext.opentelemetry_span import ( # pylint:disable=redefined-outer-name
|
| 141 |
+
OpenTelemetrySpan,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
return OpenTelemetrySpan
|
| 145 |
+
except ImportError:
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _get_opencensus_span_if_opencensus_is_imported() -> Optional[Type[AbstractSpan]]:
|
| 150 |
+
if "opencensus" not in sys.modules:
|
| 151 |
+
return None
|
| 152 |
+
return _get_opencensus_span()
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _get_opentelemetry_span_if_opentelemetry_is_imported() -> Optional[Type[AbstractSpan]]:
|
| 156 |
+
if "opentelemetry" not in sys.modules:
|
| 157 |
+
return None
|
| 158 |
+
return _get_opentelemetry_span()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
_tracing_implementation_dict: Dict[str, Callable[[], Optional[Type[AbstractSpan]]]] = {
|
| 162 |
+
"opencensus": _get_opencensus_span,
|
| 163 |
+
"opentelemetry": _get_opentelemetry_span,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def convert_tracing_impl(value: Optional[Union[str, Type[AbstractSpan]]]) -> Optional[Type[AbstractSpan]]:
|
| 168 |
+
"""Convert a string to AbstractSpan
|
| 169 |
+
|
| 170 |
+
If a AbstractSpan is passed in, it is returned as-is. Otherwise the function
|
| 171 |
+
understands the following strings, ignoring case:
|
| 172 |
+
|
| 173 |
+
* "opencensus"
|
| 174 |
+
* "opentelemetry"
|
| 175 |
+
|
| 176 |
+
:param value: the value to convert
|
| 177 |
+
:type value: string
|
| 178 |
+
:returns: AbstractSpan
|
| 179 |
+
:raises ValueError: If conversion to AbstractSpan fails
|
| 180 |
+
|
| 181 |
+
"""
|
| 182 |
+
if value is None:
|
| 183 |
+
return (
|
| 184 |
+
_get_opencensus_span_if_opencensus_is_imported() or _get_opentelemetry_span_if_opentelemetry_is_imported()
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
if not isinstance(value, str):
|
| 188 |
+
return value
|
| 189 |
+
|
| 190 |
+
value = value.lower()
|
| 191 |
+
get_wrapper_class = _tracing_implementation_dict.get(value, lambda: _unset)
|
| 192 |
+
wrapper_class: Optional[Union[_Unset, Type[AbstractSpan]]] = get_wrapper_class()
|
| 193 |
+
if wrapper_class is _unset:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
"Cannot convert {} to AbstractSpan, valid values are: {}".format(
|
| 196 |
+
value, ", ".join(_tracing_implementation_dict)
|
| 197 |
+
)
|
| 198 |
+
)
|
| 199 |
+
return wrapper_class
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class PrioritizedSetting(Generic[ValidInputType, ValueType]):
|
| 203 |
+
"""Return a value for a global setting according to configuration precedence.
|
| 204 |
+
|
| 205 |
+
The following methods are searched in order for the setting:
|
| 206 |
+
|
| 207 |
+
4. immediate values
|
| 208 |
+
3. previously user-set value
|
| 209 |
+
2. environment variable
|
| 210 |
+
1. system setting
|
| 211 |
+
0. implicit default
|
| 212 |
+
|
| 213 |
+
If a value cannot be determined, a RuntimeError is raised.
|
| 214 |
+
|
| 215 |
+
The ``env_var`` argument specifies the name of an environment to check for
|
| 216 |
+
setting values, e.g. ``"AZURE_LOG_LEVEL"``.
|
| 217 |
+
If a ``convert`` function is provided, the result will be converted before being used.
|
| 218 |
+
|
| 219 |
+
The optional ``system_hook`` can be used to specify a function that will
|
| 220 |
+
attempt to look up a value for the setting from system-wide configurations.
|
| 221 |
+
If a ``convert`` function is provided, the hook result will be converted before being used.
|
| 222 |
+
|
| 223 |
+
The optional ``default`` argument specified an implicit default value for
|
| 224 |
+
the setting that is returned if no other methods provide a value. If a ``convert`` function is provided,
|
| 225 |
+
``default`` will be converted before being used.
|
| 226 |
+
|
| 227 |
+
A ``convert`` argument may be provided to convert values before they are
|
| 228 |
+
returned. For instance to concert log levels in environment variables
|
| 229 |
+
to ``logging`` module values. If a ``convert`` function is provided, it must support
|
| 230 |
+
str as valid input type.
|
| 231 |
+
|
| 232 |
+
:param str name: the name of the setting
|
| 233 |
+
:param str env_var: the name of an environment variable to check for the setting
|
| 234 |
+
:param callable system_hook: a function that will attempt to look up a value for the setting
|
| 235 |
+
:param default: an implicit default value for the setting
|
| 236 |
+
:type default: any
|
| 237 |
+
:param callable convert: a function to convert values before they are returned
|
| 238 |
+
"""
|
| 239 |
+
|
| 240 |
+
def __init__(
|
| 241 |
+
self,
|
| 242 |
+
name: str,
|
| 243 |
+
env_var: Optional[str] = None,
|
| 244 |
+
system_hook: Optional[Callable[[], ValidInputType]] = None,
|
| 245 |
+
default: Union[ValidInputType, _Unset] = _unset,
|
| 246 |
+
convert: Optional[Callable[[Union[ValidInputType, str]], ValueType]] = None,
|
| 247 |
+
):
|
| 248 |
+
|
| 249 |
+
self._name = name
|
| 250 |
+
self._env_var = env_var
|
| 251 |
+
self._system_hook = system_hook
|
| 252 |
+
self._default = default
|
| 253 |
+
noop_convert: Callable[[Any], Any] = lambda x: x
|
| 254 |
+
self._convert: Callable[[Union[ValidInputType, str]], ValueType] = convert if convert else noop_convert
|
| 255 |
+
self._user_value: Union[ValidInputType, _Unset] = _unset
|
| 256 |
+
|
| 257 |
+
def __repr__(self) -> str:
|
| 258 |
+
return "PrioritizedSetting(%r)" % self._name
|
| 259 |
+
|
| 260 |
+
def __call__(self, value: Optional[ValidInputType] = None) -> ValueType:
|
| 261 |
+
"""Return the setting value according to the standard precedence.
|
| 262 |
+
|
| 263 |
+
:param value: value
|
| 264 |
+
:type value: str or int or float or None
|
| 265 |
+
:returns: the value of the setting
|
| 266 |
+
:rtype: str or int or float
|
| 267 |
+
:raises: RuntimeError if no value can be determined
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
# 4. immediate values
|
| 271 |
+
if value is not None:
|
| 272 |
+
return self._convert(value)
|
| 273 |
+
|
| 274 |
+
# 3. previously user-set value
|
| 275 |
+
if not isinstance(self._user_value, _Unset):
|
| 276 |
+
return self._convert(self._user_value)
|
| 277 |
+
|
| 278 |
+
# 2. environment variable
|
| 279 |
+
if self._env_var and self._env_var in os.environ:
|
| 280 |
+
return self._convert(os.environ[self._env_var])
|
| 281 |
+
|
| 282 |
+
# 1. system setting
|
| 283 |
+
if self._system_hook:
|
| 284 |
+
return self._convert(self._system_hook())
|
| 285 |
+
|
| 286 |
+
# 0. implicit default
|
| 287 |
+
if not isinstance(self._default, _Unset):
|
| 288 |
+
return self._convert(self._default)
|
| 289 |
+
|
| 290 |
+
raise RuntimeError("No configured value found for setting %r" % self._name)
|
| 291 |
+
|
| 292 |
+
def __get__(self, instance: Any, owner: Optional[Any] = None) -> PrioritizedSetting[ValidInputType, ValueType]:
|
| 293 |
+
return self
|
| 294 |
+
|
| 295 |
+
def __set__(self, instance: Any, value: ValidInputType) -> None:
|
| 296 |
+
self.set_value(value)
|
| 297 |
+
|
| 298 |
+
def set_value(self, value: ValidInputType) -> None:
|
| 299 |
+
"""Specify a value for this setting programmatically.
|
| 300 |
+
|
| 301 |
+
A value set this way takes precedence over all other methods except
|
| 302 |
+
immediate values.
|
| 303 |
+
|
| 304 |
+
:param value: a user-set value for this setting
|
| 305 |
+
:type value: str or int or float
|
| 306 |
+
"""
|
| 307 |
+
self._user_value = value
|
| 308 |
+
|
| 309 |
+
def unset_value(self) -> None:
|
| 310 |
+
"""Unset the previous user value such that the priority is reset."""
|
| 311 |
+
self._user_value = _unset
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def env_var(self) -> Optional[str]:
|
| 315 |
+
return self._env_var
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def default(self) -> Union[ValidInputType, _Unset]:
|
| 319 |
+
return self._default
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
class Settings:
|
| 323 |
+
"""Settings for globally used Azure configuration values.
|
| 324 |
+
|
| 325 |
+
You probably don't want to create an instance of this class, but call the singleton instance:
|
| 326 |
+
|
| 327 |
+
.. code-block:: python
|
| 328 |
+
|
| 329 |
+
from azure.core.settings import settings
|
| 330 |
+
settings.log_level = log_level = logging.DEBUG
|
| 331 |
+
|
| 332 |
+
The following methods are searched in order for a setting:
|
| 333 |
+
|
| 334 |
+
4. immediate values
|
| 335 |
+
3. previously user-set value
|
| 336 |
+
2. environment variable
|
| 337 |
+
1. system setting
|
| 338 |
+
0. implicit default
|
| 339 |
+
|
| 340 |
+
An implicit default is (optionally) defined by the setting attribute itself.
|
| 341 |
+
|
| 342 |
+
A system setting value can be obtained from registries or other OS configuration
|
| 343 |
+
for settings that support that method.
|
| 344 |
+
|
| 345 |
+
An environment variable value is obtained from ``os.environ``
|
| 346 |
+
|
| 347 |
+
User-set values many be specified by assigning to the attribute:
|
| 348 |
+
|
| 349 |
+
.. code-block:: python
|
| 350 |
+
|
| 351 |
+
settings.log_level = log_level = logging.DEBUG
|
| 352 |
+
|
| 353 |
+
Immediate values are (optionally) provided when the setting is retrieved:
|
| 354 |
+
|
| 355 |
+
.. code-block:: python
|
| 356 |
+
|
| 357 |
+
settings.log_level(logging.DEBUG())
|
| 358 |
+
|
| 359 |
+
Immediate values are most often useful to provide from optional arguments
|
| 360 |
+
to client functions. If the argument value is not None, it will be returned
|
| 361 |
+
as-is. Otherwise, the setting searches other methods according to the
|
| 362 |
+
precedence rules.
|
| 363 |
+
|
| 364 |
+
Immutable configuration snapshots can be created with the following methods:
|
| 365 |
+
|
| 366 |
+
* settings.defaults returns the base defaultsvalues , ignoring any environment or system
|
| 367 |
+
or user settings
|
| 368 |
+
|
| 369 |
+
* settings.current returns the current computation of settings including prioritization
|
| 370 |
+
of configuration sources, unless defaults_only is set to True (in which case the result
|
| 371 |
+
is identical to settings.defaults)
|
| 372 |
+
|
| 373 |
+
* settings.config can be called with specific values to override what settings.current
|
| 374 |
+
would provide
|
| 375 |
+
|
| 376 |
+
.. code-block:: python
|
| 377 |
+
|
| 378 |
+
# return current settings with log level overridden
|
| 379 |
+
settings.config(log_level=logging.DEBUG)
|
| 380 |
+
|
| 381 |
+
:cvar log_level: a log level to use across all Azure client SDKs (AZURE_LOG_LEVEL)
|
| 382 |
+
:type log_level: PrioritizedSetting
|
| 383 |
+
:cvar tracing_enabled: Whether tracing should be enabled across Azure SDKs (AZURE_TRACING_ENABLED)
|
| 384 |
+
:type tracing_enabled: PrioritizedSetting
|
| 385 |
+
:cvar tracing_implementation: The tracing implementation to use (AZURE_SDK_TRACING_IMPLEMENTATION)
|
| 386 |
+
:type tracing_implementation: PrioritizedSetting
|
| 387 |
+
|
| 388 |
+
:Example:
|
| 389 |
+
|
| 390 |
+
>>> import logging
|
| 391 |
+
>>> from azure.core.settings import settings
|
| 392 |
+
>>> settings.log_level = logging.DEBUG
|
| 393 |
+
>>> settings.log_level()
|
| 394 |
+
10
|
| 395 |
+
|
| 396 |
+
>>> settings.log_level(logging.WARN)
|
| 397 |
+
30
|
| 398 |
+
|
| 399 |
+
"""
|
| 400 |
+
|
| 401 |
+
def __init__(self) -> None:
|
| 402 |
+
self._defaults_only: bool = False
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def defaults_only(self) -> bool:
|
| 406 |
+
"""Whether to ignore environment and system settings and return only base default values.
|
| 407 |
+
|
| 408 |
+
:rtype: bool
|
| 409 |
+
:returns: Whether to ignore environment and system settings and return only base default values.
|
| 410 |
+
"""
|
| 411 |
+
return self._defaults_only
|
| 412 |
+
|
| 413 |
+
@defaults_only.setter
|
| 414 |
+
def defaults_only(self, value: bool) -> None:
|
| 415 |
+
self._defaults_only = value
|
| 416 |
+
|
| 417 |
+
@property
|
| 418 |
+
def defaults(self) -> Tuple[Any, ...]:
|
| 419 |
+
"""Return implicit default values for all settings, ignoring environment and system.
|
| 420 |
+
|
| 421 |
+
:rtype: namedtuple
|
| 422 |
+
:returns: The implicit default values for all settings
|
| 423 |
+
"""
|
| 424 |
+
props = {k: v.default for (k, v) in self.__class__.__dict__.items() if isinstance(v, PrioritizedSetting)}
|
| 425 |
+
return self._config(props)
|
| 426 |
+
|
| 427 |
+
@property
|
| 428 |
+
def current(self) -> Tuple[Any, ...]:
|
| 429 |
+
"""Return the current values for all settings.
|
| 430 |
+
|
| 431 |
+
:rtype: namedtuple
|
| 432 |
+
:returns: The current values for all settings
|
| 433 |
+
"""
|
| 434 |
+
if self.defaults_only:
|
| 435 |
+
return self.defaults
|
| 436 |
+
return self.config()
|
| 437 |
+
|
| 438 |
+
def config(self, **kwargs: Any) -> Tuple[Any, ...]:
|
| 439 |
+
"""Return the currently computed settings, with values overridden by parameter values.
|
| 440 |
+
|
| 441 |
+
:rtype: namedtuple
|
| 442 |
+
:returns: The current values for all settings, with values overridden by parameter values
|
| 443 |
+
|
| 444 |
+
Examples:
|
| 445 |
+
|
| 446 |
+
.. code-block:: python
|
| 447 |
+
|
| 448 |
+
# return current settings with log level overridden
|
| 449 |
+
settings.config(log_level=logging.DEBUG)
|
| 450 |
+
|
| 451 |
+
"""
|
| 452 |
+
props = {k: v() for (k, v) in self.__class__.__dict__.items() if isinstance(v, PrioritizedSetting)}
|
| 453 |
+
props.update(kwargs)
|
| 454 |
+
return self._config(props)
|
| 455 |
+
|
| 456 |
+
def _config(self, props: Mapping[str, Any]) -> Tuple[Any, ...]:
|
| 457 |
+
keys: List[str] = list(props.keys())
|
| 458 |
+
# https://github.com/python/mypy/issues/4414
|
| 459 |
+
Config = namedtuple("Config", keys) # type: ignore
|
| 460 |
+
return Config(**props)
|
| 461 |
+
|
| 462 |
+
log_level: PrioritizedSetting[Union[str, int], int] = PrioritizedSetting(
|
| 463 |
+
"log_level",
|
| 464 |
+
env_var="AZURE_LOG_LEVEL",
|
| 465 |
+
convert=convert_logging,
|
| 466 |
+
default=logging.INFO,
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
tracing_enabled: PrioritizedSetting[Union[str, bool], bool] = PrioritizedSetting(
|
| 470 |
+
"tracing_enabled",
|
| 471 |
+
env_var="AZURE_TRACING_ENABLED",
|
| 472 |
+
convert=convert_bool,
|
| 473 |
+
default=False,
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
tracing_implementation: PrioritizedSetting[
|
| 477 |
+
Optional[Union[str, Type[AbstractSpan]]], Optional[Type[AbstractSpan]]
|
| 478 |
+
] = PrioritizedSetting(
|
| 479 |
+
"tracing_implementation",
|
| 480 |
+
env_var="AZURE_SDK_TRACING_IMPLEMENTATION",
|
| 481 |
+
convert=convert_tracing_impl,
|
| 482 |
+
default=None,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
settings: Settings = Settings()
|
| 487 |
+
"""The settings unique instance.
|
| 488 |
+
|
| 489 |
+
:type settings: Settings
|
| 490 |
+
"""
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
"""Credentials for Azure SDK clients."""
|
| 6 |
+
|
| 7 |
+
from ._auth_record import AuthenticationRecord
|
| 8 |
+
from ._exceptions import AuthenticationRequiredError, CredentialUnavailableError
|
| 9 |
+
from ._constants import AzureAuthorityHosts, KnownAuthorities
|
| 10 |
+
from ._credentials import (
|
| 11 |
+
AuthorizationCodeCredential,
|
| 12 |
+
AzureDeveloperCliCredential,
|
| 13 |
+
AzureCliCredential,
|
| 14 |
+
AzurePowerShellCredential,
|
| 15 |
+
CertificateCredential,
|
| 16 |
+
ChainedTokenCredential,
|
| 17 |
+
ClientAssertionCredential,
|
| 18 |
+
ClientSecretCredential,
|
| 19 |
+
DefaultAzureCredential,
|
| 20 |
+
DeviceCodeCredential,
|
| 21 |
+
EnvironmentCredential,
|
| 22 |
+
InteractiveBrowserCredential,
|
| 23 |
+
ManagedIdentityCredential,
|
| 24 |
+
OnBehalfOfCredential,
|
| 25 |
+
SharedTokenCacheCredential,
|
| 26 |
+
UsernamePasswordCredential,
|
| 27 |
+
VisualStudioCodeCredential,
|
| 28 |
+
WorkloadIdentityCredential,
|
| 29 |
+
)
|
| 30 |
+
from ._persistent_cache import TokenCachePersistenceOptions
|
| 31 |
+
from ._bearer_token_provider import get_bearer_token_provider
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
__all__ = [
|
| 35 |
+
"AuthenticationRecord",
|
| 36 |
+
"AuthenticationRequiredError",
|
| 37 |
+
"AuthorizationCodeCredential",
|
| 38 |
+
"AzureAuthorityHosts",
|
| 39 |
+
"AzureCliCredential",
|
| 40 |
+
"AzureDeveloperCliCredential",
|
| 41 |
+
"AzurePowerShellCredential",
|
| 42 |
+
"CertificateCredential",
|
| 43 |
+
"ChainedTokenCredential",
|
| 44 |
+
"ClientAssertionCredential",
|
| 45 |
+
"ClientSecretCredential",
|
| 46 |
+
"CredentialUnavailableError",
|
| 47 |
+
"DefaultAzureCredential",
|
| 48 |
+
"DeviceCodeCredential",
|
| 49 |
+
"EnvironmentCredential",
|
| 50 |
+
"InteractiveBrowserCredential",
|
| 51 |
+
"KnownAuthorities",
|
| 52 |
+
"OnBehalfOfCredential",
|
| 53 |
+
"ManagedIdentityCredential",
|
| 54 |
+
"SharedTokenCacheCredential",
|
| 55 |
+
"TokenCachePersistenceOptions",
|
| 56 |
+
"UsernamePasswordCredential",
|
| 57 |
+
"VisualStudioCodeCredential",
|
| 58 |
+
"WorkloadIdentityCredential",
|
| 59 |
+
"get_bearer_token_provider",
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
from ._version import VERSION
|
| 63 |
+
|
| 64 |
+
__version__ = VERSION
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_auth_record.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
SUPPORTED_VERSIONS = {"1.0"}
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class AuthenticationRecord:
|
| 12 |
+
"""Non-secret account information for an authenticated user
|
| 13 |
+
|
| 14 |
+
This class enables :class:`DeviceCodeCredential` and :class:`InteractiveBrowserCredential` to access
|
| 15 |
+
previously cached authentication data. Applications shouldn't construct instances of this class. They should
|
| 16 |
+
instead acquire one from a credential's **authenticate** method, such as
|
| 17 |
+
:func:`InteractiveBrowserCredential.authenticate`. See the user_authentication sample for more details.
|
| 18 |
+
|
| 19 |
+
:param str tenant_id: The tenant the account should authenticate in.
|
| 20 |
+
:param str client_id: The client ID of the application which performed the original authentication.
|
| 21 |
+
:param str authority: The authority host used to authenticate the account.
|
| 22 |
+
:param str home_account_id: A unique identifier of the account.
|
| 23 |
+
:param str username: The user principal or service principal name of the account.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, tenant_id: str, client_id: str, authority: str, home_account_id: str, username: str) -> None:
|
| 27 |
+
self._authority = authority
|
| 28 |
+
self._client_id = client_id
|
| 29 |
+
self._home_account_id = home_account_id
|
| 30 |
+
self._tenant_id = tenant_id
|
| 31 |
+
self._username = username
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def authority(self) -> str:
|
| 35 |
+
"""The authority host used to authenticate the account.
|
| 36 |
+
|
| 37 |
+
:rtype: str
|
| 38 |
+
"""
|
| 39 |
+
return self._authority
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def client_id(self) -> str:
|
| 43 |
+
"""The client ID of the application which performed the original authentication.
|
| 44 |
+
|
| 45 |
+
:rtype: str
|
| 46 |
+
"""
|
| 47 |
+
return self._client_id
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def home_account_id(self) -> str:
|
| 51 |
+
"""A unique identifier of the account.
|
| 52 |
+
|
| 53 |
+
:rtype: str
|
| 54 |
+
"""
|
| 55 |
+
return self._home_account_id
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def tenant_id(self) -> str:
|
| 59 |
+
"""The tenant the account should authenticate in.
|
| 60 |
+
|
| 61 |
+
:rtype: str
|
| 62 |
+
"""
|
| 63 |
+
return self._tenant_id
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def username(self) -> str:
|
| 67 |
+
"""The user principal or service principal name of the account.
|
| 68 |
+
|
| 69 |
+
:rtype: str
|
| 70 |
+
"""
|
| 71 |
+
return self._username
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def deserialize(cls, data: str) -> "AuthenticationRecord":
|
| 75 |
+
"""Deserialize a record.
|
| 76 |
+
|
| 77 |
+
:param str data: A serialized record.
|
| 78 |
+
:return: The deserialized record.
|
| 79 |
+
:rtype: ~azure.identity.AuthenticationRecord
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
deserialized = json.loads(data)
|
| 83 |
+
|
| 84 |
+
version = deserialized.get("version")
|
| 85 |
+
if version not in SUPPORTED_VERSIONS:
|
| 86 |
+
raise ValueError(
|
| 87 |
+
'Unexpected version "{}". This package supports these versions: {}'.format(version, SUPPORTED_VERSIONS)
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
return cls(
|
| 91 |
+
authority=deserialized["authority"],
|
| 92 |
+
client_id=deserialized["clientId"],
|
| 93 |
+
home_account_id=deserialized["homeAccountId"],
|
| 94 |
+
tenant_id=deserialized["tenantId"],
|
| 95 |
+
username=deserialized["username"],
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def serialize(self) -> str:
|
| 99 |
+
"""Serialize the record.
|
| 100 |
+
|
| 101 |
+
:return: The serialized record.
|
| 102 |
+
:rtype: str
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
record = {
|
| 106 |
+
"authority": self._authority,
|
| 107 |
+
"clientId": self._client_id,
|
| 108 |
+
"homeAccountId": self._home_account_id,
|
| 109 |
+
"tenantId": self._tenant_id,
|
| 110 |
+
"username": self._username,
|
| 111 |
+
"version": "1.0",
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
return json.dumps(record)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_bearer_token_provider.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
from typing import Callable
|
| 6 |
+
|
| 7 |
+
from azure.core.credentials import TokenCredential
|
| 8 |
+
from azure.core.pipeline.policies import BearerTokenCredentialPolicy
|
| 9 |
+
from azure.core.pipeline import PipelineRequest, PipelineContext
|
| 10 |
+
from azure.core.rest import HttpRequest
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _make_request() -> PipelineRequest[HttpRequest]:
|
| 14 |
+
return PipelineRequest(HttpRequest("CredentialWrapper", "https://fakeurl"), PipelineContext(None))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_bearer_token_provider(credential: TokenCredential, *scopes: str) -> Callable[[], str]:
|
| 18 |
+
"""Returns a callable that provides a bearer token.
|
| 19 |
+
|
| 20 |
+
It can be used for instance to write code like:
|
| 21 |
+
|
| 22 |
+
.. code-block:: python
|
| 23 |
+
|
| 24 |
+
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
|
| 25 |
+
|
| 26 |
+
credential = DefaultAzureCredential()
|
| 27 |
+
bearer_token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default")
|
| 28 |
+
|
| 29 |
+
# Usage
|
| 30 |
+
request.headers["Authorization"] = "Bearer " + bearer_token_provider()
|
| 31 |
+
|
| 32 |
+
:param credential: The credential used to authenticate the request.
|
| 33 |
+
:type credential: ~azure.core.credentials.TokenCredential
|
| 34 |
+
:param str scopes: The scopes required for the bearer token.
|
| 35 |
+
:rtype: callable
|
| 36 |
+
:return: A callable that returns a bearer token.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
policy = BearerTokenCredentialPolicy(credential, *scopes)
|
| 40 |
+
|
| 41 |
+
def wrapper() -> str:
|
| 42 |
+
request = _make_request()
|
| 43 |
+
policy.on_request(request)
|
| 44 |
+
return request.http_request.headers["Authorization"][len("Bearer ") :]
|
| 45 |
+
|
| 46 |
+
return wrapper
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_constants.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
DEVELOPER_SIGN_ON_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
|
| 8 |
+
AZURE_VSCODE_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56"
|
| 9 |
+
VSCODE_CREDENTIALS_SECTION = "VS Code Azure"
|
| 10 |
+
DEFAULT_REFRESH_OFFSET = 300
|
| 11 |
+
DEFAULT_TOKEN_REFRESH_RETRY_DELAY = 30
|
| 12 |
+
|
| 13 |
+
CACHE_NON_CAE_SUFFIX = ".nocae" # cspell:disable-line
|
| 14 |
+
CACHE_CAE_SUFFIX = ".cae"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class AzureAuthorityHosts:
|
| 18 |
+
AZURE_CHINA = "login.chinacloudapi.cn"
|
| 19 |
+
AZURE_GERMANY = "login.microsoftonline.de"
|
| 20 |
+
AZURE_GOVERNMENT = "login.microsoftonline.us"
|
| 21 |
+
AZURE_PUBLIC_CLOUD = "login.microsoftonline.com"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class KnownAuthorities(AzureAuthorityHosts):
|
| 25 |
+
"""Alias of :class:`AzureAuthorityHosts`"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class EnvironmentVariables:
|
| 29 |
+
AZURE_CLIENT_ID = "AZURE_CLIENT_ID"
|
| 30 |
+
AZURE_CLIENT_SECRET = "AZURE_CLIENT_SECRET"
|
| 31 |
+
AZURE_TENANT_ID = "AZURE_TENANT_ID"
|
| 32 |
+
CLIENT_SECRET_VARS = (AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID)
|
| 33 |
+
|
| 34 |
+
AZURE_CLIENT_CERTIFICATE_PATH = "AZURE_CLIENT_CERTIFICATE_PATH"
|
| 35 |
+
AZURE_CLIENT_CERTIFICATE_PASSWORD = "AZURE_CLIENT_CERTIFICATE_PASSWORD"
|
| 36 |
+
CERT_VARS = (AZURE_CLIENT_ID, AZURE_CLIENT_CERTIFICATE_PATH, AZURE_TENANT_ID)
|
| 37 |
+
|
| 38 |
+
AZURE_USERNAME = "AZURE_USERNAME"
|
| 39 |
+
AZURE_PASSWORD = "AZURE_PASSWORD"
|
| 40 |
+
USERNAME_PASSWORD_VARS = (AZURE_CLIENT_ID, AZURE_USERNAME, AZURE_PASSWORD)
|
| 41 |
+
|
| 42 |
+
AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST"
|
| 43 |
+
IDENTITY_ENDPOINT = "IDENTITY_ENDPOINT"
|
| 44 |
+
IDENTITY_HEADER = "IDENTITY_HEADER"
|
| 45 |
+
IDENTITY_SERVER_THUMBPRINT = "IDENTITY_SERVER_THUMBPRINT"
|
| 46 |
+
IMDS_ENDPOINT = "IMDS_ENDPOINT"
|
| 47 |
+
MSI_ENDPOINT = "MSI_ENDPOINT"
|
| 48 |
+
MSI_SECRET = "MSI_SECRET"
|
| 49 |
+
|
| 50 |
+
AZURE_AUTHORITY_HOST = "AZURE_AUTHORITY_HOST"
|
| 51 |
+
AZURE_IDENTITY_DISABLE_MULTITENANTAUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH"
|
| 52 |
+
AZURE_REGIONAL_AUTHORITY_NAME = "AZURE_REGIONAL_AUTHORITY_NAME"
|
| 53 |
+
|
| 54 |
+
AZURE_FEDERATED_TOKEN_FILE = "AZURE_FEDERATED_TOKEN_FILE"
|
| 55 |
+
WORKLOAD_IDENTITY_VARS = (AZURE_AUTHORITY_HOST, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_enums.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
from enum import Enum
|
| 6 |
+
from azure.core import CaseInsensitiveEnumMeta
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RegionalAuthority(str, Enum, metaclass=CaseInsensitiveEnumMeta):
|
| 10 |
+
"""Identifies a regional authority for authentication"""
|
| 11 |
+
|
| 12 |
+
#: Attempt to discover the appropriate authority. This works on some Azure hosts, such as VMs and
|
| 13 |
+
#: Azure Functions. The non-regional authority is used when discovery fails.
|
| 14 |
+
AUTO_DISCOVER_REGION = "tryautodetect"
|
| 15 |
+
|
| 16 |
+
ASIA_EAST = "eastasia"
|
| 17 |
+
ASIA_SOUTHEAST = "southeastasia"
|
| 18 |
+
AUSTRALIA_CENTRAL = "australiacentral"
|
| 19 |
+
AUSTRALIA_CENTRAL_2 = "australiacentral2"
|
| 20 |
+
AUSTRALIA_EAST = "australiaeast"
|
| 21 |
+
AUSTRALIA_SOUTHEAST = "australiasoutheast"
|
| 22 |
+
BRAZIL_SOUTH = "brazilsouth"
|
| 23 |
+
CANADA_CENTRAL = "canadacentral"
|
| 24 |
+
CANADA_EAST = "canadaeast"
|
| 25 |
+
CHINA_EAST = "chinaeast"
|
| 26 |
+
CHINA_EAST_2 = "chinaeast2"
|
| 27 |
+
CHINA_NORTH = "chinanorth"
|
| 28 |
+
CHINA_NORTH_2 = "chinanorth2"
|
| 29 |
+
EUROPE_NORTH = "northeurope"
|
| 30 |
+
EUROPE_WEST = "westeurope"
|
| 31 |
+
FRANCE_CENTRAL = "francecentral"
|
| 32 |
+
FRANCE_SOUTH = "francesouth"
|
| 33 |
+
GERMANY_CENTRAL = "germanycentral"
|
| 34 |
+
GERMANY_NORTH = "germanynorth"
|
| 35 |
+
GERMANY_NORTHEAST = "germanynortheast"
|
| 36 |
+
GERMANY_WEST_CENTRAL = "germanywestcentral"
|
| 37 |
+
GOVERNMENT_US_ARIZONA = "usgovarizona"
|
| 38 |
+
GOVERNMENT_US_DOD_CENTRAL = "usdodcentral"
|
| 39 |
+
GOVERNMENT_US_DOD_EAST = "usdodeast"
|
| 40 |
+
GOVERNMENT_US_IOWA = "usgoviowa"
|
| 41 |
+
GOVERNMENT_US_TEXAS = "usgovtexas"
|
| 42 |
+
GOVERNMENT_US_VIRGINIA = "usgovvirginia"
|
| 43 |
+
INDIA_CENTRAL = "centralindia"
|
| 44 |
+
INDIA_SOUTH = "southindia"
|
| 45 |
+
INDIA_WEST = "westindia"
|
| 46 |
+
JAPAN_EAST = "japaneast"
|
| 47 |
+
JAPAN_WEST = "japanwest"
|
| 48 |
+
KOREA_CENTRAL = "koreacentral"
|
| 49 |
+
KOREA_SOUTH = "koreasouth"
|
| 50 |
+
NORWAY_EAST = "norwayeast"
|
| 51 |
+
NORWAY_WEST = "norwaywest"
|
| 52 |
+
SOUTH_AFRICA_NORTH = "southafricanorth"
|
| 53 |
+
SOUTH_AFRICA_WEST = "southafricawest"
|
| 54 |
+
SWITZERLAND_NORTH = "switzerlandnorth"
|
| 55 |
+
SWITZERLAND_WEST = "switzerlandwest"
|
| 56 |
+
UAE_CENTRAL = "uaecentral"
|
| 57 |
+
UAE_NORTH = "uaenorth"
|
| 58 |
+
UK_SOUTH = "uksouth"
|
| 59 |
+
UK_WEST = "ukwest"
|
| 60 |
+
US_CENTRAL = "centralus"
|
| 61 |
+
US_EAST = "eastus"
|
| 62 |
+
US_EAST_2 = "eastus2"
|
| 63 |
+
US_NORTH_CENTRAL = "northcentralus"
|
| 64 |
+
US_SOUTH_CENTRAL = "southcentralus"
|
| 65 |
+
US_WEST = "westus"
|
| 66 |
+
US_WEST_2 = "westus2"
|
| 67 |
+
US_WEST_CENTRAL = "westcentralus"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_exceptions.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
from typing import Any, Iterable, Optional
|
| 6 |
+
|
| 7 |
+
from azure.core.exceptions import ClientAuthenticationError
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CredentialUnavailableError(ClientAuthenticationError):
|
| 11 |
+
"""The credential did not attempt to authenticate because required data or state is unavailable."""
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AuthenticationRequiredError(CredentialUnavailableError):
|
| 15 |
+
"""Interactive authentication is required to acquire a token.
|
| 16 |
+
|
| 17 |
+
This error is raised only by interactive user credentials configured not to automatically prompt for user
|
| 18 |
+
interaction as needed. Its properties provide additional information that may be required to authenticate. The
|
| 19 |
+
control_interactive_prompts sample demonstrates handling this error by calling a credential's "authenticate"
|
| 20 |
+
method.
|
| 21 |
+
|
| 22 |
+
:param str scopes: Scopes requested during the failed authentication
|
| 23 |
+
:param str message: An error message explaining the reason for the exception.
|
| 24 |
+
:param str claims: Additional claims required in the next authentication.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(
|
| 28 |
+
self, scopes: Iterable[str], message: Optional[str] = None, claims: Optional[str] = None, **kwargs: Any
|
| 29 |
+
) -> None:
|
| 30 |
+
self._claims = claims
|
| 31 |
+
self._scopes = scopes
|
| 32 |
+
if not message:
|
| 33 |
+
message = "Interactive authentication is required to get a token. Call 'authenticate' to begin."
|
| 34 |
+
super(AuthenticationRequiredError, self).__init__(message=message, **kwargs)
|
| 35 |
+
|
| 36 |
+
@property
|
| 37 |
+
def scopes(self) -> Iterable[str]:
|
| 38 |
+
"""Scopes requested during the failed authentication.
|
| 39 |
+
|
| 40 |
+
:rtype: ~typing.Iterable[str]
|
| 41 |
+
"""
|
| 42 |
+
return self._scopes
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def claims(self) -> Optional[str]:
|
| 46 |
+
"""Additional claims required in the next authentication.
|
| 47 |
+
|
| 48 |
+
:rtype: str or None
|
| 49 |
+
"""
|
| 50 |
+
return self._claims
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_persistent_cache.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
from typing import TYPE_CHECKING, Any
|
| 9 |
+
|
| 10 |
+
from ._constants import CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
import msal_extensions
|
| 14 |
+
|
| 15 |
+
_LOGGER = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TokenCachePersistenceOptions:
|
| 19 |
+
"""Options for persistent token caching.
|
| 20 |
+
|
| 21 |
+
Most credentials accept an instance of this class to configure persistent token caching. The default values
|
| 22 |
+
configure a credential to use a cache shared with Microsoft developer tools and
|
| 23 |
+
:class:`~azure.identity.SharedTokenCacheCredential`. To isolate a credential's data from other applications,
|
| 24 |
+
specify a `name` for the cache.
|
| 25 |
+
|
| 26 |
+
By default, the cache is encrypted with the current platform's user data protection API, and will raise an error
|
| 27 |
+
when this is not available. To configure the cache to fall back to an unencrypted file instead of raising an
|
| 28 |
+
error, specify `allow_unencrypted_storage=True`.
|
| 29 |
+
|
| 30 |
+
.. warning:: The cache contains authentication secrets. If the cache is not encrypted, protecting it is the
|
| 31 |
+
application's responsibility. A breach of its contents will fully compromise accounts.
|
| 32 |
+
|
| 33 |
+
.. admonition:: Example:
|
| 34 |
+
|
| 35 |
+
.. literalinclude:: ../tests/test_persistent_cache.py
|
| 36 |
+
:start-after: [START snippet]
|
| 37 |
+
:end-before: [END snippet]
|
| 38 |
+
:language: python
|
| 39 |
+
:caption: Configuring a credential for persistent caching
|
| 40 |
+
:dedent: 8
|
| 41 |
+
|
| 42 |
+
:keyword str name: prefix name of the cache, used to isolate its data from other applications. Defaults to the
|
| 43 |
+
name of the cache shared by Microsoft dev tools and :class:`~azure.identity.SharedTokenCacheCredential`.
|
| 44 |
+
Additional strings may be appended to the name for further isolation.
|
| 45 |
+
:keyword bool allow_unencrypted_storage: whether the cache should fall back to storing its data in plain text when
|
| 46 |
+
encryption isn't possible. False by default. Setting this to True does not disable encryption. The cache will
|
| 47 |
+
always try to encrypt its data.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self, *, allow_unencrypted_storage: bool = False, name: str = "msal.cache", **kwargs: Any) -> None:
|
| 51 |
+
# pylint:disable=unused-argument
|
| 52 |
+
self.allow_unencrypted_storage = allow_unencrypted_storage
|
| 53 |
+
self.name = name
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _load_persistent_cache(
|
| 57 |
+
options: TokenCachePersistenceOptions, is_cae: bool = False
|
| 58 |
+
) -> "msal_extensions.PersistedTokenCache":
|
| 59 |
+
import msal_extensions
|
| 60 |
+
|
| 61 |
+
cache_suffix = CACHE_CAE_SUFFIX if is_cae else CACHE_NON_CAE_SUFFIX
|
| 62 |
+
persistence = _get_persistence(
|
| 63 |
+
allow_unencrypted=options.allow_unencrypted_storage,
|
| 64 |
+
account_name="MSALCache",
|
| 65 |
+
cache_name=options.name + cache_suffix,
|
| 66 |
+
)
|
| 67 |
+
return msal_extensions.PersistedTokenCache(persistence)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _get_persistence(allow_unencrypted, account_name, cache_name):
|
| 71 |
+
# type: (bool, str, str) -> msal_extensions.persistence.BasePersistence
|
| 72 |
+
"""Get an msal_extensions persistence instance for the current platform.
|
| 73 |
+
|
| 74 |
+
On Windows the cache is a file protected by the Data Protection API. On Linux and macOS the cache is stored by
|
| 75 |
+
libsecret and Keychain, respectively. On those platforms the cache uses the modified timestamp of a file on disk to
|
| 76 |
+
decide whether to reload the cache.
|
| 77 |
+
|
| 78 |
+
:param bool allow_unencrypted: when True, the cache will be kept in plaintext should encryption be impossible in the
|
| 79 |
+
current environment
|
| 80 |
+
:param str account_name: the name of the account for which the cache is storing tokens
|
| 81 |
+
:param str cache_name: the name of the cache
|
| 82 |
+
:return: an msal_extensions persistence instance
|
| 83 |
+
:rtype: ~msal_extensions.persistence.BasePersistence
|
| 84 |
+
"""
|
| 85 |
+
import msal_extensions
|
| 86 |
+
|
| 87 |
+
if sys.platform.startswith("win") and "LOCALAPPDATA" in os.environ:
|
| 88 |
+
cache_location = os.path.join(os.environ["LOCALAPPDATA"], ".IdentityService", cache_name)
|
| 89 |
+
return msal_extensions.FilePersistenceWithDataProtection(cache_location)
|
| 90 |
+
|
| 91 |
+
if sys.platform.startswith("darwin"):
|
| 92 |
+
# the cache uses this file's modified timestamp to decide whether to reload
|
| 93 |
+
file_path = os.path.expanduser(os.path.join("~", ".IdentityService", cache_name))
|
| 94 |
+
return msal_extensions.KeychainPersistence(file_path, "Microsoft.Developer.IdentityService", account_name)
|
| 95 |
+
|
| 96 |
+
if sys.platform.startswith("linux"):
|
| 97 |
+
# The cache uses this file's modified timestamp to decide whether to reload. Note this path is the same
|
| 98 |
+
# as that of the plaintext fallback: a new encrypted cache will stomp an unencrypted cache.
|
| 99 |
+
file_path = os.path.expanduser(os.path.join("~", ".IdentityService", cache_name))
|
| 100 |
+
try:
|
| 101 |
+
return msal_extensions.LibsecretPersistence(
|
| 102 |
+
file_path, cache_name, {"MsalClientID": "Microsoft.Developer.IdentityService"}, label=account_name
|
| 103 |
+
)
|
| 104 |
+
except Exception as ex: # pylint:disable=broad-except
|
| 105 |
+
_LOGGER.debug('msal-extensions is unable to encrypt a persistent cache: "%s"', ex, exc_info=True)
|
| 106 |
+
if not allow_unencrypted:
|
| 107 |
+
error = ValueError(
|
| 108 |
+
"Cache encryption is impossible because libsecret dependencies are not installed or are unusable,"
|
| 109 |
+
+ " for example because no display is available (as in an SSH session). The chained exception has"
|
| 110 |
+
+ ' more information. Specify "allow_unencrypted_storage=True" to store the cache unencrypted'
|
| 111 |
+
+ " instead of raising this exception."
|
| 112 |
+
)
|
| 113 |
+
raise error from ex
|
| 114 |
+
return msal_extensions.FilePersistence(file_path)
|
| 115 |
+
|
| 116 |
+
raise NotImplementedError("A persistent cache is not available in this environment.")
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/_version.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ------------------------------------
|
| 2 |
+
# Copyright (c) Microsoft Corporation.
|
| 3 |
+
# Licensed under the MIT License.
|
| 4 |
+
# ------------------------------------
|
| 5 |
+
VERSION = "1.15.0"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/identity/py.typed
ADDED
|
File without changes
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/__init__.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
from ._version import VERSION
|
| 29 |
+
from ._pipeline_client import ARMPipelineClient
|
| 30 |
+
from ._async_pipeline_client import AsyncARMPipelineClient
|
| 31 |
+
|
| 32 |
+
__all__ = ["ARMPipelineClient", "AsyncARMPipelineClient"]
|
| 33 |
+
__version__ = VERSION
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_async_pipeline_client.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from collections.abc import Iterable
|
| 27 |
+
from azure.core import AsyncPipelineClient
|
| 28 |
+
from .policies import (
|
| 29 |
+
AsyncARMAutoResourceProviderRegistrationPolicy,
|
| 30 |
+
ARMHttpLoggingPolicy,
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AsyncARMPipelineClient(AsyncPipelineClient):
|
| 35 |
+
"""A pipeline client designed for ARM explicitly.
|
| 36 |
+
|
| 37 |
+
:param str base_url: URL for the request.
|
| 38 |
+
:keyword AsyncPipeline pipeline: If omitted, a Pipeline object is created and returned.
|
| 39 |
+
:keyword list[AsyncHTTPPolicy] policies: If omitted, the standard policies of the configuration object is used.
|
| 40 |
+
:keyword per_call_policies: If specified, the policies will be added into the policy list before RetryPolicy
|
| 41 |
+
:paramtype per_call_policies: Union[AsyncHTTPPolicy, SansIOHTTPPolicy,
|
| 42 |
+
list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]
|
| 43 |
+
:keyword per_retry_policies: If specified, the policies will be added into the policy list after RetryPolicy
|
| 44 |
+
:paramtype per_retry_policies: Union[AsyncHTTPPolicy, SansIOHTTPPolicy,
|
| 45 |
+
list[AsyncHTTPPolicy], list[SansIOHTTPPolicy]]
|
| 46 |
+
:keyword AsyncHttpTransport transport: If omitted, AioHttpTransport is used for asynchronous transport.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, base_url, **kwargs):
|
| 50 |
+
if "policies" not in kwargs:
|
| 51 |
+
if "config" not in kwargs:
|
| 52 |
+
raise ValueError("Current implementation requires to pass 'config' if you don't pass 'policies'")
|
| 53 |
+
per_call_policies = kwargs.get("per_call_policies", [])
|
| 54 |
+
if isinstance(per_call_policies, Iterable):
|
| 55 |
+
per_call_policies.append(AsyncARMAutoResourceProviderRegistrationPolicy())
|
| 56 |
+
else:
|
| 57 |
+
per_call_policies = [
|
| 58 |
+
per_call_policies,
|
| 59 |
+
AsyncARMAutoResourceProviderRegistrationPolicy(),
|
| 60 |
+
]
|
| 61 |
+
kwargs["per_call_policies"] = per_call_policies
|
| 62 |
+
config = kwargs.get("config")
|
| 63 |
+
if not config.http_logging_policy:
|
| 64 |
+
config.http_logging_policy = kwargs.get("http_logging_policy", ARMHttpLoggingPolicy(**kwargs))
|
| 65 |
+
kwargs["config"] = config
|
| 66 |
+
super(AsyncARMPipelineClient, self).__init__(base_url, **kwargs)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_pipeline_client.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
from collections.abc import Iterable
|
| 27 |
+
from azure.core import PipelineClient
|
| 28 |
+
from .policies import ARMAutoResourceProviderRegistrationPolicy, ARMHttpLoggingPolicy
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ARMPipelineClient(PipelineClient):
|
| 32 |
+
"""A pipeline client designed for ARM explicitly.
|
| 33 |
+
|
| 34 |
+
:param str base_url: URL for the request.
|
| 35 |
+
:keyword Pipeline pipeline: If omitted, a Pipeline object is created and returned.
|
| 36 |
+
:keyword list[HTTPPolicy] policies: If omitted, the standard policies of the configuration object is used.
|
| 37 |
+
:keyword per_call_policies: If specified, the policies will be added into the policy list before RetryPolicy
|
| 38 |
+
:paramtype per_call_policies: Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]
|
| 39 |
+
:keyword per_retry_policies: If specified, the policies will be added into the policy list after RetryPolicy
|
| 40 |
+
:paramtype per_retry_policies: Union[HTTPPolicy, SansIOHTTPPolicy, list[HTTPPolicy], list[SansIOHTTPPolicy]]
|
| 41 |
+
:keyword HttpTransport transport: If omitted, RequestsTransport is used for synchronous transport.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, base_url, **kwargs):
|
| 45 |
+
if "policies" not in kwargs:
|
| 46 |
+
if "config" not in kwargs:
|
| 47 |
+
raise ValueError("Current implementation requires to pass 'config' if you don't pass 'policies'")
|
| 48 |
+
per_call_policies = kwargs.get("per_call_policies", [])
|
| 49 |
+
if isinstance(per_call_policies, Iterable):
|
| 50 |
+
per_call_policies.append(ARMAutoResourceProviderRegistrationPolicy())
|
| 51 |
+
else:
|
| 52 |
+
per_call_policies = [
|
| 53 |
+
per_call_policies,
|
| 54 |
+
ARMAutoResourceProviderRegistrationPolicy(),
|
| 55 |
+
]
|
| 56 |
+
kwargs["per_call_policies"] = per_call_policies
|
| 57 |
+
config = kwargs.get("config")
|
| 58 |
+
if not config.http_logging_policy:
|
| 59 |
+
config.http_logging_policy = kwargs.get("http_logging_policy", ARMHttpLoggingPolicy(**kwargs))
|
| 60 |
+
kwargs["config"] = config
|
| 61 |
+
super(ARMPipelineClient, self).__init__(base_url, **kwargs)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/_version.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
#
|
| 7 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 8 |
+
# Changes may cause incorrect behavior and will be lost if the code is
|
| 9 |
+
# regenerated.
|
| 10 |
+
# --------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
VERSION = "1.4.0"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/exceptions.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
from azure.core.exceptions import ODataV4Format
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
_LOGGER = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class TypedErrorInfo:
|
| 38 |
+
"""Additional info class defined in ARM specification.
|
| 39 |
+
|
| 40 |
+
https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-details.md#error-response-content
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def __init__(self, type, info): # pylint: disable=redefined-builtin
|
| 44 |
+
self.type = type
|
| 45 |
+
self.info = info
|
| 46 |
+
|
| 47 |
+
def __str__(self):
|
| 48 |
+
"""Cloud error message."""
|
| 49 |
+
error_str = "Type: {}".format(self.type)
|
| 50 |
+
error_str += "\nInfo: {}".format(json.dumps(self.info, indent=4))
|
| 51 |
+
return error_str
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ARMErrorFormat(ODataV4Format):
|
| 55 |
+
"""Describe error format from ARM, used at the base or inside "details" node.
|
| 56 |
+
|
| 57 |
+
This format is compatible with ODataV4 format.
|
| 58 |
+
https://github.com/Azure/azure-resource-manager-rpc/blob/master/v1.0/common-api-details.md#error-response-content
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
def __init__(self, json_object):
|
| 62 |
+
# Parse the ODatav4 part
|
| 63 |
+
super(ARMErrorFormat, self).__init__(json_object)
|
| 64 |
+
if "error" in json_object:
|
| 65 |
+
json_object = json_object["error"]
|
| 66 |
+
|
| 67 |
+
# ARM specific annotations
|
| 68 |
+
self.additional_info = [
|
| 69 |
+
TypedErrorInfo(additional_info["type"], additional_info["info"])
|
| 70 |
+
for additional_info in json_object.get("additionalInfo", [])
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
def __str__(self):
|
| 74 |
+
error_str = super(ARMErrorFormat, self).__str__()
|
| 75 |
+
|
| 76 |
+
if self.additional_info:
|
| 77 |
+
error_str += "\nAdditional Information:"
|
| 78 |
+
for error_info in self.additional_info:
|
| 79 |
+
error_str += str(error_info)
|
| 80 |
+
|
| 81 |
+
return error_str
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/py.typed
ADDED
|
File without changes
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/core/tools.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
import re
|
| 28 |
+
import logging
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
_LOGGER = logging.getLogger(__name__)
|
| 32 |
+
_ARMID_RE = re.compile(
|
| 33 |
+
"(?i)/subscriptions/(?P<subscription>[^/]+)(/resourceGroups/(?P<resource_group>[^/]+))?"
|
| 34 |
+
"(/providers/(?P<namespace>[^/]+)/(?P<type>[^/]*)/(?P<name>[^/]+)(?P<children>.*))?"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
_CHILDREN_RE = re.compile("(?i)(/providers/(?P<child_namespace>[^/]+))?/" "(?P<child_type>[^/]*)/(?P<child_name>[^/]+)")
|
| 38 |
+
|
| 39 |
+
_ARMNAME_RE = re.compile("^[^<>%&:\\?/]{1,260}$")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
__all__ = [
|
| 43 |
+
"parse_resource_id",
|
| 44 |
+
"resource_id",
|
| 45 |
+
"is_valid_resource_id",
|
| 46 |
+
"is_valid_resource_name",
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parse_resource_id(rid):
|
| 51 |
+
"""Parses a resource_id into its various parts.
|
| 52 |
+
|
| 53 |
+
Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
|
| 54 |
+
|
| 55 |
+
:param rid: The resource id being parsed
|
| 56 |
+
:type rid: str
|
| 57 |
+
:returns: A dictionary with with following key/value pairs (if found):
|
| 58 |
+
|
| 59 |
+
- subscription: Subscription id
|
| 60 |
+
- resource_group: Name of resource group
|
| 61 |
+
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
|
| 62 |
+
- type: Type of the root resource (i.e. virtualMachines)
|
| 63 |
+
- name: Name of the root resource
|
| 64 |
+
- child_namespace_{level}: Namespace for the child resource of that level
|
| 65 |
+
- child_type_{level}: Type of the child resource of that level
|
| 66 |
+
- child_name_{level}: Name of the child resource of that level
|
| 67 |
+
- last_child_num: Level of the last child
|
| 68 |
+
- resource_parent: Computed parent in the following pattern: providers/{namespace}\
|
| 69 |
+
/{parent}/{type}/{name}
|
| 70 |
+
- resource_namespace: Same as namespace. Note that this may be different than the \
|
| 71 |
+
target resource's namespace.
|
| 72 |
+
- resource_type: Type of the target resource (not the parent)
|
| 73 |
+
- resource_name: Name of the target resource (not the parent)
|
| 74 |
+
|
| 75 |
+
:rtype: dict[str,str]
|
| 76 |
+
"""
|
| 77 |
+
if not rid:
|
| 78 |
+
return {}
|
| 79 |
+
match = _ARMID_RE.match(rid)
|
| 80 |
+
if match:
|
| 81 |
+
result = match.groupdict()
|
| 82 |
+
children = _CHILDREN_RE.finditer(result["children"] or "")
|
| 83 |
+
count = None
|
| 84 |
+
for count, child in enumerate(children):
|
| 85 |
+
result.update({key + "_%d" % (count + 1): group for key, group in child.groupdict().items()})
|
| 86 |
+
result["last_child_num"] = count + 1 if isinstance(count, int) else None
|
| 87 |
+
result = _populate_alternate_kwargs(result)
|
| 88 |
+
else:
|
| 89 |
+
result = dict(name=rid)
|
| 90 |
+
return {key: value for key, value in result.items() if value is not None}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _populate_alternate_kwargs(kwargs):
|
| 94 |
+
"""Translates the parsed arguments into a format used by generic ARM commands
|
| 95 |
+
such as the resource and lock commands.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
resource_namespace = kwargs["namespace"]
|
| 99 |
+
resource_type = kwargs.get("child_type_{}".format(kwargs["last_child_num"])) or kwargs["type"]
|
| 100 |
+
resource_name = kwargs.get("child_name_{}".format(kwargs["last_child_num"])) or kwargs["name"]
|
| 101 |
+
|
| 102 |
+
_get_parents_from_parts(kwargs)
|
| 103 |
+
kwargs["resource_namespace"] = resource_namespace
|
| 104 |
+
kwargs["resource_type"] = resource_type
|
| 105 |
+
kwargs["resource_name"] = resource_name
|
| 106 |
+
return kwargs
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _get_parents_from_parts(kwargs):
|
| 110 |
+
"""Get the parents given all the children parameters."""
|
| 111 |
+
parent_builder = []
|
| 112 |
+
if kwargs["last_child_num"] is not None:
|
| 113 |
+
parent_builder.append("{type}/{name}/".format(**kwargs))
|
| 114 |
+
for index in range(1, kwargs["last_child_num"]):
|
| 115 |
+
child_namespace = kwargs.get("child_namespace_{}".format(index))
|
| 116 |
+
if child_namespace is not None:
|
| 117 |
+
parent_builder.append("providers/{}/".format(child_namespace))
|
| 118 |
+
kwargs["child_parent_{}".format(index)] = "".join(parent_builder)
|
| 119 |
+
parent_builder.append("{{child_type_{0}}}/{{child_name_{0}}}/".format(index).format(**kwargs))
|
| 120 |
+
child_namespace = kwargs.get("child_namespace_{}".format(kwargs["last_child_num"]))
|
| 121 |
+
if child_namespace is not None:
|
| 122 |
+
parent_builder.append("providers/{}/".format(child_namespace))
|
| 123 |
+
kwargs["child_parent_{}".format(kwargs["last_child_num"])] = "".join(parent_builder)
|
| 124 |
+
kwargs["resource_parent"] = "".join(parent_builder) if kwargs["name"] else None
|
| 125 |
+
return kwargs
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def resource_id(**kwargs):
|
| 129 |
+
"""Create a valid resource id string from the given parts.
|
| 130 |
+
|
| 131 |
+
This method builds the resource id from the left until the next required id parameter
|
| 132 |
+
to be appended is not found. It then returns the built up id.
|
| 133 |
+
|
| 134 |
+
:param dict kwargs: The keyword arguments that will make up the id.
|
| 135 |
+
|
| 136 |
+
The method accepts the following keyword arguments:
|
| 137 |
+
- subscription (required): Subscription id
|
| 138 |
+
- resource_group: Name of resource group
|
| 139 |
+
- namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
|
| 140 |
+
- type: Type of the resource (i.e. virtualMachines)
|
| 141 |
+
- name: Name of the resource (or parent if child_name is also \
|
| 142 |
+
specified)
|
| 143 |
+
- child_namespace_{level}: Namespace for the child resource of that level (optional)
|
| 144 |
+
- child_type_{level}: Type of the child resource of that level
|
| 145 |
+
- child_name_{level}: Name of the child resource of that level
|
| 146 |
+
|
| 147 |
+
:returns: A resource id built from the given arguments.
|
| 148 |
+
:rtype: str
|
| 149 |
+
"""
|
| 150 |
+
kwargs = {k: v for k, v in kwargs.items() if v is not None}
|
| 151 |
+
rid_builder = ["/subscriptions/{subscription}".format(**kwargs)]
|
| 152 |
+
try:
|
| 153 |
+
try:
|
| 154 |
+
rid_builder.append("resourceGroups/{resource_group}".format(**kwargs))
|
| 155 |
+
except KeyError:
|
| 156 |
+
pass
|
| 157 |
+
rid_builder.append("providers/{namespace}".format(**kwargs))
|
| 158 |
+
rid_builder.append("{type}/{name}".format(**kwargs))
|
| 159 |
+
count = 1
|
| 160 |
+
while True:
|
| 161 |
+
try:
|
| 162 |
+
rid_builder.append("providers/{{child_namespace_{}}}".format(count).format(**kwargs))
|
| 163 |
+
except KeyError:
|
| 164 |
+
pass
|
| 165 |
+
rid_builder.append("{{child_type_{0}}}/{{child_name_{0}}}".format(count).format(**kwargs))
|
| 166 |
+
count += 1
|
| 167 |
+
except KeyError:
|
| 168 |
+
pass
|
| 169 |
+
return "/".join(rid_builder)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def is_valid_resource_id(rid, exception_type=None):
|
| 173 |
+
"""Validates the given resource id.
|
| 174 |
+
|
| 175 |
+
:param rid: The resource id being validated.
|
| 176 |
+
:type rid: str
|
| 177 |
+
:param exception_type: Raises this Exception if invalid.
|
| 178 |
+
:type exception_type: :class:`Exception`
|
| 179 |
+
:returns: A boolean describing whether the id is valid.
|
| 180 |
+
:rtype: bool
|
| 181 |
+
"""
|
| 182 |
+
is_valid = False
|
| 183 |
+
try:
|
| 184 |
+
is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower()
|
| 185 |
+
except KeyError:
|
| 186 |
+
pass
|
| 187 |
+
if not is_valid and exception_type:
|
| 188 |
+
raise exception_type()
|
| 189 |
+
return is_valid
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def is_valid_resource_name(rname, exception_type=None):
|
| 193 |
+
"""Validates the given resource name to ARM guidelines, individual services may be more restrictive.
|
| 194 |
+
|
| 195 |
+
:param rname: The resource name being validated.
|
| 196 |
+
:type rname: str
|
| 197 |
+
:param exception_type: Raises this Exception if invalid.
|
| 198 |
+
:type exception_type: :class:`Exception`
|
| 199 |
+
:returns: A boolean describing whether the name is valid.
|
| 200 |
+
:rtype: bool
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
match = _ARMNAME_RE.match(rname)
|
| 204 |
+
|
| 205 |
+
if match:
|
| 206 |
+
return True
|
| 207 |
+
if exception_type:
|
| 208 |
+
raise exception_type()
|
| 209 |
+
return False
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
__version__="0.0.1"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/rdbms/_version.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
VERSION = "10.1.0"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for license information.
|
| 5 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 6 |
+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
| 7 |
+
# --------------------------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
from .managedapplications import ApplicationClient
|
| 10 |
+
from .deploymentscripts import DeploymentScriptsClient
|
| 11 |
+
from .features import FeatureClient
|
| 12 |
+
from .links import ManagementLinkClient
|
| 13 |
+
from .locks import ManagementLockClient
|
| 14 |
+
from .policy import PolicyClient
|
| 15 |
+
from .resources import ResourceManagementClient
|
| 16 |
+
from .subscriptions import SubscriptionClient
|
| 17 |
+
__all__ = ['ApplicationClient',
|
| 18 |
+
'DeploymentScriptsClient',
|
| 19 |
+
'FeatureClient',
|
| 20 |
+
'PolicyClient',
|
| 21 |
+
'ManagementLinkClient',
|
| 22 |
+
'ManagementLockClient',
|
| 23 |
+
'ResourceManagementClient',
|
| 24 |
+
'SubscriptionClient']
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/_version.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
VERSION = "23.0.1"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for license information.
|
| 5 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 6 |
+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
| 7 |
+
# --------------------------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
from ._changes_client import ChangesClient
|
| 10 |
+
__all__ = ['ChangesClient']
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from ._patch import patch_sdk # type: ignore
|
| 14 |
+
patch_sdk()
|
| 15 |
+
except ImportError:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
from ._version import VERSION
|
| 19 |
+
|
| 20 |
+
__version__ = VERSION
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_changes_client.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
#
|
| 7 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 8 |
+
# Changes may cause incorrect behavior and will be lost if the code is
|
| 9 |
+
# regenerated.
|
| 10 |
+
# --------------------------------------------------------------------------
|
| 11 |
+
|
| 12 |
+
from typing import Any, Optional, TYPE_CHECKING
|
| 13 |
+
|
| 14 |
+
from azure.mgmt.core import ARMPipelineClient
|
| 15 |
+
from azure.profiles import KnownProfiles, ProfileDefinition
|
| 16 |
+
from azure.profiles.multiapiclient import MultiApiClientMixin
|
| 17 |
+
|
| 18 |
+
from ._configuration import ChangesClientConfiguration
|
| 19 |
+
from ._serialization import Deserializer, Serializer
|
| 20 |
+
|
| 21 |
+
if TYPE_CHECKING:
|
| 22 |
+
# pylint: disable=unused-import,ungrouped-imports
|
| 23 |
+
from azure.core.credentials import TokenCredential
|
| 24 |
+
|
| 25 |
+
class _SDKClient(object):
|
| 26 |
+
def __init__(self, *args, **kwargs):
|
| 27 |
+
"""This is a fake class to support current implemetation of MultiApiClientMixin."
|
| 28 |
+
Will be removed in final version of multiapi azure-core based client
|
| 29 |
+
"""
|
| 30 |
+
pass
|
| 31 |
+
|
| 32 |
+
class ChangesClient(MultiApiClientMixin, _SDKClient):
|
| 33 |
+
"""The Resource Changes Client.
|
| 34 |
+
|
| 35 |
+
This ready contains multiple API versions, to help you deal with all of the Azure clouds
|
| 36 |
+
(Azure Stack, Azure Government, Azure China, etc.).
|
| 37 |
+
By default, it uses the latest API version available on public Azure.
|
| 38 |
+
For production, you should stick to a particular api-version and/or profile.
|
| 39 |
+
The profile sets a mapping between an operation group and its API version.
|
| 40 |
+
The api-version parameter sets the default API version if the operation
|
| 41 |
+
group is not described in the profile.
|
| 42 |
+
|
| 43 |
+
:param credential: Credential needed for the client to connect to Azure. Required.
|
| 44 |
+
:type credential: ~azure.core.credentials.TokenCredential
|
| 45 |
+
:param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required.
|
| 46 |
+
:type subscription_id: str
|
| 47 |
+
:param api_version: API version to use if no profile is provided, or if missing in profile.
|
| 48 |
+
:type api_version: str
|
| 49 |
+
:param base_url: Service URL
|
| 50 |
+
:type base_url: str
|
| 51 |
+
:param profile: A profile definition, from KnownProfiles to dict.
|
| 52 |
+
:type profile: azure.profiles.KnownProfiles
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
DEFAULT_API_VERSION = '2022-05-01'
|
| 56 |
+
_PROFILE_TAG = "azure.mgmt.resource.changes.ChangesClient"
|
| 57 |
+
LATEST_PROFILE = ProfileDefinition({
|
| 58 |
+
_PROFILE_TAG: {
|
| 59 |
+
None: DEFAULT_API_VERSION,
|
| 60 |
+
}},
|
| 61 |
+
_PROFILE_TAG + " latest"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
def __init__(
|
| 65 |
+
self,
|
| 66 |
+
credential: "TokenCredential",
|
| 67 |
+
subscription_id: str,
|
| 68 |
+
api_version: Optional[str]=None,
|
| 69 |
+
base_url: str = "https://management.azure.com",
|
| 70 |
+
profile: KnownProfiles=KnownProfiles.default,
|
| 71 |
+
**kwargs: Any
|
| 72 |
+
):
|
| 73 |
+
self._config = ChangesClientConfiguration(credential, subscription_id, **kwargs)
|
| 74 |
+
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
|
| 75 |
+
super(ChangesClient, self).__init__(
|
| 76 |
+
api_version=api_version,
|
| 77 |
+
profile=profile
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def _models_dict(cls, api_version):
|
| 82 |
+
return {k: v for k, v in cls.models(api_version).__dict__.items() if isinstance(v, type)}
|
| 83 |
+
|
| 84 |
+
@classmethod
|
| 85 |
+
def models(cls, api_version=DEFAULT_API_VERSION):
|
| 86 |
+
"""Module depends on the API version:
|
| 87 |
+
|
| 88 |
+
* 2022-05-01: :mod:`v2022_05_01.models<azure.mgmt.resource.changes.v2022_05_01.models>`
|
| 89 |
+
"""
|
| 90 |
+
if api_version == '2022-05-01':
|
| 91 |
+
from .v2022_05_01 import models
|
| 92 |
+
return models
|
| 93 |
+
raise ValueError("API version {} is not available".format(api_version))
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def changes(self):
|
| 97 |
+
"""Instance depends on the API version:
|
| 98 |
+
|
| 99 |
+
* 2022-05-01: :class:`ChangesOperations<azure.mgmt.resource.changes.v2022_05_01.operations.ChangesOperations>`
|
| 100 |
+
"""
|
| 101 |
+
api_version = self._get_api_version('changes')
|
| 102 |
+
if api_version == '2022-05-01':
|
| 103 |
+
from .v2022_05_01.operations import ChangesOperations as OperationClass
|
| 104 |
+
else:
|
| 105 |
+
raise ValueError("API version {} does not have operation group 'changes'".format(api_version))
|
| 106 |
+
self._config.api_version = api_version
|
| 107 |
+
return OperationClass(self._client, self._config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
| 108 |
+
|
| 109 |
+
def close(self):
|
| 110 |
+
self._client.close()
|
| 111 |
+
def __enter__(self):
|
| 112 |
+
self._client.__enter__()
|
| 113 |
+
return self
|
| 114 |
+
def __exit__(self, *exc_details):
|
| 115 |
+
self._client.__exit__(*exc_details)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_configuration.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
#
|
| 7 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 8 |
+
# Changes may cause incorrect behavior and will be lost if the code is
|
| 9 |
+
# regenerated.
|
| 10 |
+
# --------------------------------------------------------------------------
|
| 11 |
+
from typing import Any, TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
from azure.core.configuration import Configuration
|
| 14 |
+
from azure.core.pipeline import policies
|
| 15 |
+
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
|
| 16 |
+
|
| 17 |
+
from ._version import VERSION
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
# pylint: disable=unused-import,ungrouped-imports
|
| 21 |
+
from azure.core.credentials import TokenCredential
|
| 22 |
+
|
| 23 |
+
class ChangesClientConfiguration(Configuration):
|
| 24 |
+
"""Configuration for ChangesClient.
|
| 25 |
+
|
| 26 |
+
Note that all parameters used to create this instance are saved as instance
|
| 27 |
+
attributes.
|
| 28 |
+
|
| 29 |
+
:param credential: Credential needed for the client to connect to Azure. Required.
|
| 30 |
+
:type credential: ~azure.core.credentials.TokenCredential
|
| 31 |
+
:param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000). Required.
|
| 32 |
+
:type subscription_id: str
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
credential: "TokenCredential",
|
| 38 |
+
subscription_id: str,
|
| 39 |
+
**kwargs: Any
|
| 40 |
+
):
|
| 41 |
+
if credential is None:
|
| 42 |
+
raise ValueError("Parameter 'credential' must not be None.")
|
| 43 |
+
if subscription_id is None:
|
| 44 |
+
raise ValueError("Parameter 'subscription_id' must not be None.")
|
| 45 |
+
super(ChangesClientConfiguration, self).__init__(**kwargs)
|
| 46 |
+
|
| 47 |
+
self.credential = credential
|
| 48 |
+
self.subscription_id = subscription_id
|
| 49 |
+
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
|
| 50 |
+
kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION))
|
| 51 |
+
self._configure(**kwargs)
|
| 52 |
+
|
| 53 |
+
def _configure(
|
| 54 |
+
self,
|
| 55 |
+
**kwargs: Any
|
| 56 |
+
):
|
| 57 |
+
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
|
| 58 |
+
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
|
| 59 |
+
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
|
| 60 |
+
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
|
| 61 |
+
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
|
| 62 |
+
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
|
| 63 |
+
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
|
| 64 |
+
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
|
| 65 |
+
self.authentication_policy = kwargs.get('authentication_policy')
|
| 66 |
+
if self.credential and not self.authentication_policy:
|
| 67 |
+
self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_serialization.py
ADDED
|
@@ -0,0 +1,1998 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# --------------------------------------------------------------------------
|
| 2 |
+
#
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# The MIT License (MIT)
|
| 6 |
+
#
|
| 7 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 8 |
+
# of this software and associated documentation files (the ""Software""), to
|
| 9 |
+
# deal in the Software without restriction, including without limitation the
|
| 10 |
+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 11 |
+
# sell copies of the Software, and to permit persons to whom the Software is
|
| 12 |
+
# furnished to do so, subject to the following conditions:
|
| 13 |
+
#
|
| 14 |
+
# The above copyright notice and this permission notice shall be included in
|
| 15 |
+
# all copies or substantial portions of the Software.
|
| 16 |
+
#
|
| 17 |
+
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 18 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 19 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 20 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 21 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 22 |
+
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 23 |
+
# IN THE SOFTWARE.
|
| 24 |
+
#
|
| 25 |
+
# --------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
# pylint: skip-file
|
| 28 |
+
# pyright: reportUnnecessaryTypeIgnoreComment=false
|
| 29 |
+
|
| 30 |
+
from base64 import b64decode, b64encode
|
| 31 |
+
import calendar
|
| 32 |
+
import datetime
|
| 33 |
+
import decimal
|
| 34 |
+
import email
|
| 35 |
+
from enum import Enum
|
| 36 |
+
import json
|
| 37 |
+
import logging
|
| 38 |
+
import re
|
| 39 |
+
import sys
|
| 40 |
+
import codecs
|
| 41 |
+
from typing import (
|
| 42 |
+
Dict,
|
| 43 |
+
Any,
|
| 44 |
+
cast,
|
| 45 |
+
Optional,
|
| 46 |
+
Union,
|
| 47 |
+
AnyStr,
|
| 48 |
+
IO,
|
| 49 |
+
Mapping,
|
| 50 |
+
Callable,
|
| 51 |
+
TypeVar,
|
| 52 |
+
MutableMapping,
|
| 53 |
+
Type,
|
| 54 |
+
List,
|
| 55 |
+
Mapping,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
try:
|
| 59 |
+
from urllib import quote # type: ignore
|
| 60 |
+
except ImportError:
|
| 61 |
+
from urllib.parse import quote
|
| 62 |
+
import xml.etree.ElementTree as ET
|
| 63 |
+
|
| 64 |
+
import isodate # type: ignore
|
| 65 |
+
|
| 66 |
+
from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback
|
| 67 |
+
from azure.core.serialization import NULL as AzureCoreNull
|
| 68 |
+
|
| 69 |
+
_BOM = codecs.BOM_UTF8.decode(encoding="utf-8")
|
| 70 |
+
|
| 71 |
+
ModelType = TypeVar("ModelType", bound="Model")
|
| 72 |
+
JSON = MutableMapping[str, Any]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class RawDeserializer:
|
| 76 |
+
|
| 77 |
+
# Accept "text" because we're open minded people...
|
| 78 |
+
JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$")
|
| 79 |
+
|
| 80 |
+
# Name used in context
|
| 81 |
+
CONTEXT_NAME = "deserialized_data"
|
| 82 |
+
|
| 83 |
+
@classmethod
|
| 84 |
+
def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any:
|
| 85 |
+
"""Decode data according to content-type.
|
| 86 |
+
|
| 87 |
+
Accept a stream of data as well, but will be load at once in memory for now.
|
| 88 |
+
|
| 89 |
+
If no content-type, will return the string version (not bytes, not stream)
|
| 90 |
+
|
| 91 |
+
:param data: Input, could be bytes or stream (will be decoded with UTF8) or text
|
| 92 |
+
:type data: str or bytes or IO
|
| 93 |
+
:param str content_type: The content type.
|
| 94 |
+
"""
|
| 95 |
+
if hasattr(data, "read"):
|
| 96 |
+
# Assume a stream
|
| 97 |
+
data = cast(IO, data).read()
|
| 98 |
+
|
| 99 |
+
if isinstance(data, bytes):
|
| 100 |
+
data_as_str = data.decode(encoding="utf-8-sig")
|
| 101 |
+
else:
|
| 102 |
+
# Explain to mypy the correct type.
|
| 103 |
+
data_as_str = cast(str, data)
|
| 104 |
+
|
| 105 |
+
# Remove Byte Order Mark if present in string
|
| 106 |
+
data_as_str = data_as_str.lstrip(_BOM)
|
| 107 |
+
|
| 108 |
+
if content_type is None:
|
| 109 |
+
return data
|
| 110 |
+
|
| 111 |
+
if cls.JSON_REGEXP.match(content_type):
|
| 112 |
+
try:
|
| 113 |
+
return json.loads(data_as_str)
|
| 114 |
+
except ValueError as err:
|
| 115 |
+
raise DeserializationError("JSON is invalid: {}".format(err), err)
|
| 116 |
+
elif "xml" in (content_type or []):
|
| 117 |
+
try:
|
| 118 |
+
|
| 119 |
+
try:
|
| 120 |
+
if isinstance(data, unicode): # type: ignore
|
| 121 |
+
# If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string
|
| 122 |
+
data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore
|
| 123 |
+
except NameError:
|
| 124 |
+
pass
|
| 125 |
+
|
| 126 |
+
return ET.fromstring(data_as_str) # nosec
|
| 127 |
+
except ET.ParseError:
|
| 128 |
+
# It might be because the server has an issue, and returned JSON with
|
| 129 |
+
# content-type XML....
|
| 130 |
+
# So let's try a JSON load, and if it's still broken
|
| 131 |
+
# let's flow the initial exception
|
| 132 |
+
def _json_attemp(data):
|
| 133 |
+
try:
|
| 134 |
+
return True, json.loads(data)
|
| 135 |
+
except ValueError:
|
| 136 |
+
return False, None # Don't care about this one
|
| 137 |
+
|
| 138 |
+
success, json_result = _json_attemp(data)
|
| 139 |
+
if success:
|
| 140 |
+
return json_result
|
| 141 |
+
# If i'm here, it's not JSON, it's not XML, let's scream
|
| 142 |
+
# and raise the last context in this block (the XML exception)
|
| 143 |
+
# The function hack is because Py2.7 messes up with exception
|
| 144 |
+
# context otherwise.
|
| 145 |
+
_LOGGER.critical("Wasn't XML not JSON, failing")
|
| 146 |
+
raise_with_traceback(DeserializationError, "XML is invalid")
|
| 147 |
+
raise DeserializationError("Cannot deserialize content-type: {}".format(content_type))
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any:
|
| 151 |
+
"""Deserialize from HTTP response.
|
| 152 |
+
|
| 153 |
+
Use bytes and headers to NOT use any requests/aiohttp or whatever
|
| 154 |
+
specific implementation.
|
| 155 |
+
Headers will tested for "content-type"
|
| 156 |
+
"""
|
| 157 |
+
# Try to use content-type from headers if available
|
| 158 |
+
content_type = None
|
| 159 |
+
if "content-type" in headers:
|
| 160 |
+
content_type = headers["content-type"].split(";")[0].strip().lower()
|
| 161 |
+
# Ouch, this server did not declare what it sent...
|
| 162 |
+
# Let's guess it's JSON...
|
| 163 |
+
# Also, since Autorest was considering that an empty body was a valid JSON,
|
| 164 |
+
# need that test as well....
|
| 165 |
+
else:
|
| 166 |
+
content_type = "application/json"
|
| 167 |
+
|
| 168 |
+
if body_bytes:
|
| 169 |
+
return cls.deserialize_from_text(body_bytes, content_type)
|
| 170 |
+
return None
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
basestring # type: ignore
|
| 175 |
+
unicode_str = unicode # type: ignore
|
| 176 |
+
except NameError:
|
| 177 |
+
basestring = str
|
| 178 |
+
unicode_str = str
|
| 179 |
+
|
| 180 |
+
_LOGGER = logging.getLogger(__name__)
|
| 181 |
+
|
| 182 |
+
try:
|
| 183 |
+
_long_type = long # type: ignore
|
| 184 |
+
except NameError:
|
| 185 |
+
_long_type = int
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class UTC(datetime.tzinfo):
|
| 189 |
+
"""Time Zone info for handling UTC"""
|
| 190 |
+
|
| 191 |
+
def utcoffset(self, dt):
|
| 192 |
+
"""UTF offset for UTC is 0."""
|
| 193 |
+
return datetime.timedelta(0)
|
| 194 |
+
|
| 195 |
+
def tzname(self, dt):
|
| 196 |
+
"""Timestamp representation."""
|
| 197 |
+
return "Z"
|
| 198 |
+
|
| 199 |
+
def dst(self, dt):
|
| 200 |
+
"""No daylight saving for UTC."""
|
| 201 |
+
return datetime.timedelta(hours=1)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
try:
|
| 205 |
+
from datetime import timezone as _FixedOffset # type: ignore
|
| 206 |
+
except ImportError: # Python 2.7
|
| 207 |
+
|
| 208 |
+
class _FixedOffset(datetime.tzinfo): # type: ignore
|
| 209 |
+
"""Fixed offset in minutes east from UTC.
|
| 210 |
+
Copy/pasted from Python doc
|
| 211 |
+
:param datetime.timedelta offset: offset in timedelta format
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def __init__(self, offset):
|
| 215 |
+
self.__offset = offset
|
| 216 |
+
|
| 217 |
+
def utcoffset(self, dt):
|
| 218 |
+
return self.__offset
|
| 219 |
+
|
| 220 |
+
def tzname(self, dt):
|
| 221 |
+
return str(self.__offset.total_seconds() / 3600)
|
| 222 |
+
|
| 223 |
+
def __repr__(self):
|
| 224 |
+
return "<FixedOffset {}>".format(self.tzname(None))
|
| 225 |
+
|
| 226 |
+
def dst(self, dt):
|
| 227 |
+
return datetime.timedelta(0)
|
| 228 |
+
|
| 229 |
+
def __getinitargs__(self):
|
| 230 |
+
return (self.__offset,)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
try:
|
| 234 |
+
from datetime import timezone
|
| 235 |
+
|
| 236 |
+
TZ_UTC = timezone.utc
|
| 237 |
+
except ImportError:
|
| 238 |
+
TZ_UTC = UTC() # type: ignore
|
| 239 |
+
|
| 240 |
+
_FLATTEN = re.compile(r"(?<!\\)\.")
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def attribute_transformer(key, attr_desc, value):
|
| 244 |
+
"""A key transformer that returns the Python attribute.
|
| 245 |
+
|
| 246 |
+
:param str key: The attribute name
|
| 247 |
+
:param dict attr_desc: The attribute metadata
|
| 248 |
+
:param object value: The value
|
| 249 |
+
:returns: A key using attribute name
|
| 250 |
+
"""
|
| 251 |
+
return (key, value)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def full_restapi_key_transformer(key, attr_desc, value):
|
| 255 |
+
"""A key transformer that returns the full RestAPI key path.
|
| 256 |
+
|
| 257 |
+
:param str _: The attribute name
|
| 258 |
+
:param dict attr_desc: The attribute metadata
|
| 259 |
+
:param object value: The value
|
| 260 |
+
:returns: A list of keys using RestAPI syntax.
|
| 261 |
+
"""
|
| 262 |
+
keys = _FLATTEN.split(attr_desc["key"])
|
| 263 |
+
return ([_decode_attribute_map_key(k) for k in keys], value)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def last_restapi_key_transformer(key, attr_desc, value):
|
| 267 |
+
"""A key transformer that returns the last RestAPI key.
|
| 268 |
+
|
| 269 |
+
:param str key: The attribute name
|
| 270 |
+
:param dict attr_desc: The attribute metadata
|
| 271 |
+
:param object value: The value
|
| 272 |
+
:returns: The last RestAPI key.
|
| 273 |
+
"""
|
| 274 |
+
key, value = full_restapi_key_transformer(key, attr_desc, value)
|
| 275 |
+
return (key[-1], value)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _create_xml_node(tag, prefix=None, ns=None):
|
| 279 |
+
"""Create a XML node."""
|
| 280 |
+
if prefix and ns:
|
| 281 |
+
ET.register_namespace(prefix, ns)
|
| 282 |
+
if ns:
|
| 283 |
+
return ET.Element("{" + ns + "}" + tag)
|
| 284 |
+
else:
|
| 285 |
+
return ET.Element(tag)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class Model(object):
|
| 289 |
+
"""Mixin for all client request body/response body models to support
|
| 290 |
+
serialization and deserialization.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
_subtype_map: Dict[str, Dict[str, Any]] = {}
|
| 294 |
+
_attribute_map: Dict[str, Dict[str, Any]] = {}
|
| 295 |
+
_validation: Dict[str, Dict[str, Any]] = {}
|
| 296 |
+
|
| 297 |
+
def __init__(self, **kwargs: Any) -> None:
|
| 298 |
+
self.additional_properties: Dict[str, Any] = {}
|
| 299 |
+
for k in kwargs:
|
| 300 |
+
if k not in self._attribute_map:
|
| 301 |
+
_LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__)
|
| 302 |
+
elif k in self._validation and self._validation[k].get("readonly", False):
|
| 303 |
+
_LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__)
|
| 304 |
+
else:
|
| 305 |
+
setattr(self, k, kwargs[k])
|
| 306 |
+
|
| 307 |
+
def __eq__(self, other: Any) -> bool:
|
| 308 |
+
"""Compare objects by comparing all attributes."""
|
| 309 |
+
if isinstance(other, self.__class__):
|
| 310 |
+
return self.__dict__ == other.__dict__
|
| 311 |
+
return False
|
| 312 |
+
|
| 313 |
+
def __ne__(self, other: Any) -> bool:
|
| 314 |
+
"""Compare objects by comparing all attributes."""
|
| 315 |
+
return not self.__eq__(other)
|
| 316 |
+
|
| 317 |
+
def __str__(self) -> str:
|
| 318 |
+
return str(self.__dict__)
|
| 319 |
+
|
| 320 |
+
@classmethod
|
| 321 |
+
def enable_additional_properties_sending(cls) -> None:
|
| 322 |
+
cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"}
|
| 323 |
+
|
| 324 |
+
@classmethod
|
| 325 |
+
def is_xml_model(cls) -> bool:
|
| 326 |
+
try:
|
| 327 |
+
cls._xml_map # type: ignore
|
| 328 |
+
except AttributeError:
|
| 329 |
+
return False
|
| 330 |
+
return True
|
| 331 |
+
|
| 332 |
+
@classmethod
|
| 333 |
+
def _create_xml_node(cls):
|
| 334 |
+
"""Create XML node."""
|
| 335 |
+
try:
|
| 336 |
+
xml_map = cls._xml_map # type: ignore
|
| 337 |
+
except AttributeError:
|
| 338 |
+
xml_map = {}
|
| 339 |
+
|
| 340 |
+
return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None))
|
| 341 |
+
|
| 342 |
+
def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON:
|
| 343 |
+
"""Return the JSON that would be sent to azure from this model.
|
| 344 |
+
|
| 345 |
+
This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`.
|
| 346 |
+
|
| 347 |
+
If you want XML serialization, you can pass the kwargs is_xml=True.
|
| 348 |
+
|
| 349 |
+
:param bool keep_readonly: If you want to serialize the readonly attributes
|
| 350 |
+
:returns: A dict JSON compatible object
|
| 351 |
+
:rtype: dict
|
| 352 |
+
"""
|
| 353 |
+
serializer = Serializer(self._infer_class_models())
|
| 354 |
+
return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs)
|
| 355 |
+
|
| 356 |
+
def as_dict(
|
| 357 |
+
self,
|
| 358 |
+
keep_readonly: bool = True,
|
| 359 |
+
key_transformer: Callable[
|
| 360 |
+
[str, Dict[str, Any], Any], Any
|
| 361 |
+
] = attribute_transformer,
|
| 362 |
+
**kwargs: Any
|
| 363 |
+
) -> JSON:
|
| 364 |
+
"""Return a dict that can be serialized using json.dump.
|
| 365 |
+
|
| 366 |
+
Advanced usage might optionally use a callback as parameter:
|
| 367 |
+
|
| 368 |
+
.. code::python
|
| 369 |
+
|
| 370 |
+
def my_key_transformer(key, attr_desc, value):
|
| 371 |
+
return key
|
| 372 |
+
|
| 373 |
+
Key is the attribute name used in Python. Attr_desc
|
| 374 |
+
is a dict of metadata. Currently contains 'type' with the
|
| 375 |
+
msrest type and 'key' with the RestAPI encoded key.
|
| 376 |
+
Value is the current value in this object.
|
| 377 |
+
|
| 378 |
+
The string returned will be used to serialize the key.
|
| 379 |
+
If the return type is a list, this is considered hierarchical
|
| 380 |
+
result dict.
|
| 381 |
+
|
| 382 |
+
See the three examples in this file:
|
| 383 |
+
|
| 384 |
+
- attribute_transformer
|
| 385 |
+
- full_restapi_key_transformer
|
| 386 |
+
- last_restapi_key_transformer
|
| 387 |
+
|
| 388 |
+
If you want XML serialization, you can pass the kwargs is_xml=True.
|
| 389 |
+
|
| 390 |
+
:param function key_transformer: A key transformer function.
|
| 391 |
+
:returns: A dict JSON compatible object
|
| 392 |
+
:rtype: dict
|
| 393 |
+
"""
|
| 394 |
+
serializer = Serializer(self._infer_class_models())
|
| 395 |
+
return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs)
|
| 396 |
+
|
| 397 |
+
@classmethod
|
| 398 |
+
def _infer_class_models(cls):
|
| 399 |
+
try:
|
| 400 |
+
str_models = cls.__module__.rsplit(".", 1)[0]
|
| 401 |
+
models = sys.modules[str_models]
|
| 402 |
+
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
|
| 403 |
+
if cls.__name__ not in client_models:
|
| 404 |
+
raise ValueError("Not Autorest generated code")
|
| 405 |
+
except Exception:
|
| 406 |
+
# Assume it's not Autorest generated (tests?). Add ourselves as dependencies.
|
| 407 |
+
client_models = {cls.__name__: cls}
|
| 408 |
+
return client_models
|
| 409 |
+
|
| 410 |
+
@classmethod
|
| 411 |
+
def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType:
|
| 412 |
+
"""Parse a str using the RestAPI syntax and return a model.
|
| 413 |
+
|
| 414 |
+
:param str data: A str using RestAPI structure. JSON by default.
|
| 415 |
+
:param str content_type: JSON by default, set application/xml if XML.
|
| 416 |
+
:returns: An instance of this model
|
| 417 |
+
:raises: DeserializationError if something went wrong
|
| 418 |
+
"""
|
| 419 |
+
deserializer = Deserializer(cls._infer_class_models())
|
| 420 |
+
return deserializer(cls.__name__, data, content_type=content_type)
|
| 421 |
+
|
| 422 |
+
@classmethod
|
| 423 |
+
def from_dict(
|
| 424 |
+
cls: Type[ModelType],
|
| 425 |
+
data: Any,
|
| 426 |
+
key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None,
|
| 427 |
+
content_type: Optional[str] = None,
|
| 428 |
+
) -> ModelType:
|
| 429 |
+
"""Parse a dict using given key extractor return a model.
|
| 430 |
+
|
| 431 |
+
By default consider key
|
| 432 |
+
extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor
|
| 433 |
+
and last_rest_key_case_insensitive_extractor)
|
| 434 |
+
|
| 435 |
+
:param dict data: A dict using RestAPI structure
|
| 436 |
+
:param str content_type: JSON by default, set application/xml if XML.
|
| 437 |
+
:returns: An instance of this model
|
| 438 |
+
:raises: DeserializationError if something went wrong
|
| 439 |
+
"""
|
| 440 |
+
deserializer = Deserializer(cls._infer_class_models())
|
| 441 |
+
deserializer.key_extractors = ( # type: ignore
|
| 442 |
+
[ # type: ignore
|
| 443 |
+
attribute_key_case_insensitive_extractor,
|
| 444 |
+
rest_key_case_insensitive_extractor,
|
| 445 |
+
last_rest_key_case_insensitive_extractor,
|
| 446 |
+
]
|
| 447 |
+
if key_extractors is None
|
| 448 |
+
else key_extractors
|
| 449 |
+
)
|
| 450 |
+
return deserializer(cls.__name__, data, content_type=content_type)
|
| 451 |
+
|
| 452 |
+
@classmethod
|
| 453 |
+
def _flatten_subtype(cls, key, objects):
|
| 454 |
+
if "_subtype_map" not in cls.__dict__:
|
| 455 |
+
return {}
|
| 456 |
+
result = dict(cls._subtype_map[key])
|
| 457 |
+
for valuetype in cls._subtype_map[key].values():
|
| 458 |
+
result.update(objects[valuetype]._flatten_subtype(key, objects))
|
| 459 |
+
return result
|
| 460 |
+
|
| 461 |
+
@classmethod
|
| 462 |
+
def _classify(cls, response, objects):
|
| 463 |
+
"""Check the class _subtype_map for any child classes.
|
| 464 |
+
We want to ignore any inherited _subtype_maps.
|
| 465 |
+
Remove the polymorphic key from the initial data.
|
| 466 |
+
"""
|
| 467 |
+
for subtype_key in cls.__dict__.get("_subtype_map", {}).keys():
|
| 468 |
+
subtype_value = None
|
| 469 |
+
|
| 470 |
+
if not isinstance(response, ET.Element):
|
| 471 |
+
rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1]
|
| 472 |
+
subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None)
|
| 473 |
+
else:
|
| 474 |
+
subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response)
|
| 475 |
+
if subtype_value:
|
| 476 |
+
# Try to match base class. Can be class name only
|
| 477 |
+
# (bug to fix in Autorest to support x-ms-discriminator-name)
|
| 478 |
+
if cls.__name__ == subtype_value:
|
| 479 |
+
return cls
|
| 480 |
+
flatten_mapping_type = cls._flatten_subtype(subtype_key, objects)
|
| 481 |
+
try:
|
| 482 |
+
return objects[flatten_mapping_type[subtype_value]] # type: ignore
|
| 483 |
+
except KeyError:
|
| 484 |
+
_LOGGER.warning(
|
| 485 |
+
"Subtype value %s has no mapping, use base class %s.",
|
| 486 |
+
subtype_value,
|
| 487 |
+
cls.__name__,
|
| 488 |
+
)
|
| 489 |
+
break
|
| 490 |
+
else:
|
| 491 |
+
_LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__)
|
| 492 |
+
break
|
| 493 |
+
return cls
|
| 494 |
+
|
| 495 |
+
@classmethod
|
| 496 |
+
def _get_rest_key_parts(cls, attr_key):
|
| 497 |
+
"""Get the RestAPI key of this attr, split it and decode part
|
| 498 |
+
:param str attr_key: Attribute key must be in attribute_map.
|
| 499 |
+
:returns: A list of RestAPI part
|
| 500 |
+
:rtype: list
|
| 501 |
+
"""
|
| 502 |
+
rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"])
|
| 503 |
+
return [_decode_attribute_map_key(key_part) for key_part in rest_split_key]
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def _decode_attribute_map_key(key):
|
| 507 |
+
"""This decode a key in an _attribute_map to the actual key we want to look at
|
| 508 |
+
inside the received data.
|
| 509 |
+
|
| 510 |
+
:param str key: A key string from the generated code
|
| 511 |
+
"""
|
| 512 |
+
return key.replace("\\.", ".")
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class Serializer(object):
|
| 516 |
+
"""Request object model serializer."""
|
| 517 |
+
|
| 518 |
+
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
|
| 519 |
+
|
| 520 |
+
_xml_basic_types_serializers = {"bool": lambda x: str(x).lower()}
|
| 521 |
+
days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"}
|
| 522 |
+
months = {
|
| 523 |
+
1: "Jan",
|
| 524 |
+
2: "Feb",
|
| 525 |
+
3: "Mar",
|
| 526 |
+
4: "Apr",
|
| 527 |
+
5: "May",
|
| 528 |
+
6: "Jun",
|
| 529 |
+
7: "Jul",
|
| 530 |
+
8: "Aug",
|
| 531 |
+
9: "Sep",
|
| 532 |
+
10: "Oct",
|
| 533 |
+
11: "Nov",
|
| 534 |
+
12: "Dec",
|
| 535 |
+
}
|
| 536 |
+
validation = {
|
| 537 |
+
"min_length": lambda x, y: len(x) < y,
|
| 538 |
+
"max_length": lambda x, y: len(x) > y,
|
| 539 |
+
"minimum": lambda x, y: x < y,
|
| 540 |
+
"maximum": lambda x, y: x > y,
|
| 541 |
+
"minimum_ex": lambda x, y: x <= y,
|
| 542 |
+
"maximum_ex": lambda x, y: x >= y,
|
| 543 |
+
"min_items": lambda x, y: len(x) < y,
|
| 544 |
+
"max_items": lambda x, y: len(x) > y,
|
| 545 |
+
"pattern": lambda x, y: not re.match(y, x, re.UNICODE),
|
| 546 |
+
"unique": lambda x, y: len(x) != len(set(x)),
|
| 547 |
+
"multiple": lambda x, y: x % y != 0,
|
| 548 |
+
}
|
| 549 |
+
|
| 550 |
+
def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]]=None):
|
| 551 |
+
self.serialize_type = {
|
| 552 |
+
"iso-8601": Serializer.serialize_iso,
|
| 553 |
+
"rfc-1123": Serializer.serialize_rfc,
|
| 554 |
+
"unix-time": Serializer.serialize_unix,
|
| 555 |
+
"duration": Serializer.serialize_duration,
|
| 556 |
+
"date": Serializer.serialize_date,
|
| 557 |
+
"time": Serializer.serialize_time,
|
| 558 |
+
"decimal": Serializer.serialize_decimal,
|
| 559 |
+
"long": Serializer.serialize_long,
|
| 560 |
+
"bytearray": Serializer.serialize_bytearray,
|
| 561 |
+
"base64": Serializer.serialize_base64,
|
| 562 |
+
"object": self.serialize_object,
|
| 563 |
+
"[]": self.serialize_iter,
|
| 564 |
+
"{}": self.serialize_dict,
|
| 565 |
+
}
|
| 566 |
+
self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {}
|
| 567 |
+
self.key_transformer = full_restapi_key_transformer
|
| 568 |
+
self.client_side_validation = True
|
| 569 |
+
|
| 570 |
+
def _serialize(self, target_obj, data_type=None, **kwargs):
|
| 571 |
+
"""Serialize data into a string according to type.
|
| 572 |
+
|
| 573 |
+
:param target_obj: The data to be serialized.
|
| 574 |
+
:param str data_type: The type to be serialized from.
|
| 575 |
+
:rtype: str, dict
|
| 576 |
+
:raises: SerializationError if serialization fails.
|
| 577 |
+
"""
|
| 578 |
+
key_transformer = kwargs.get("key_transformer", self.key_transformer)
|
| 579 |
+
keep_readonly = kwargs.get("keep_readonly", False)
|
| 580 |
+
if target_obj is None:
|
| 581 |
+
return None
|
| 582 |
+
|
| 583 |
+
attr_name = None
|
| 584 |
+
class_name = target_obj.__class__.__name__
|
| 585 |
+
|
| 586 |
+
if data_type:
|
| 587 |
+
return self.serialize_data(target_obj, data_type, **kwargs)
|
| 588 |
+
|
| 589 |
+
if not hasattr(target_obj, "_attribute_map"):
|
| 590 |
+
data_type = type(target_obj).__name__
|
| 591 |
+
if data_type in self.basic_types.values():
|
| 592 |
+
return self.serialize_data(target_obj, data_type, **kwargs)
|
| 593 |
+
|
| 594 |
+
# Force "is_xml" kwargs if we detect a XML model
|
| 595 |
+
try:
|
| 596 |
+
is_xml_model_serialization = kwargs["is_xml"]
|
| 597 |
+
except KeyError:
|
| 598 |
+
is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model())
|
| 599 |
+
|
| 600 |
+
serialized = {}
|
| 601 |
+
if is_xml_model_serialization:
|
| 602 |
+
serialized = target_obj._create_xml_node()
|
| 603 |
+
try:
|
| 604 |
+
attributes = target_obj._attribute_map
|
| 605 |
+
for attr, attr_desc in attributes.items():
|
| 606 |
+
attr_name = attr
|
| 607 |
+
if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False):
|
| 608 |
+
continue
|
| 609 |
+
|
| 610 |
+
if attr_name == "additional_properties" and attr_desc["key"] == "":
|
| 611 |
+
if target_obj.additional_properties is not None:
|
| 612 |
+
serialized.update(target_obj.additional_properties)
|
| 613 |
+
continue
|
| 614 |
+
try:
|
| 615 |
+
|
| 616 |
+
orig_attr = getattr(target_obj, attr)
|
| 617 |
+
if is_xml_model_serialization:
|
| 618 |
+
pass # Don't provide "transformer" for XML for now. Keep "orig_attr"
|
| 619 |
+
else: # JSON
|
| 620 |
+
keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr)
|
| 621 |
+
keys = keys if isinstance(keys, list) else [keys]
|
| 622 |
+
|
| 623 |
+
kwargs["serialization_ctxt"] = attr_desc
|
| 624 |
+
new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs)
|
| 625 |
+
|
| 626 |
+
if is_xml_model_serialization:
|
| 627 |
+
xml_desc = attr_desc.get("xml", {})
|
| 628 |
+
xml_name = xml_desc.get("name", attr_desc["key"])
|
| 629 |
+
xml_prefix = xml_desc.get("prefix", None)
|
| 630 |
+
xml_ns = xml_desc.get("ns", None)
|
| 631 |
+
if xml_desc.get("attr", False):
|
| 632 |
+
if xml_ns:
|
| 633 |
+
ET.register_namespace(xml_prefix, xml_ns)
|
| 634 |
+
xml_name = "{}{}".format(xml_ns, xml_name)
|
| 635 |
+
serialized.set(xml_name, new_attr) # type: ignore
|
| 636 |
+
continue
|
| 637 |
+
if xml_desc.get("text", False):
|
| 638 |
+
serialized.text = new_attr # type: ignore
|
| 639 |
+
continue
|
| 640 |
+
if isinstance(new_attr, list):
|
| 641 |
+
serialized.extend(new_attr) # type: ignore
|
| 642 |
+
elif isinstance(new_attr, ET.Element):
|
| 643 |
+
# If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces.
|
| 644 |
+
if "name" not in getattr(orig_attr, "_xml_map", {}):
|
| 645 |
+
splitted_tag = new_attr.tag.split("}")
|
| 646 |
+
if len(splitted_tag) == 2: # Namespace
|
| 647 |
+
new_attr.tag = "}".join([splitted_tag[0], xml_name])
|
| 648 |
+
else:
|
| 649 |
+
new_attr.tag = xml_name
|
| 650 |
+
serialized.append(new_attr) # type: ignore
|
| 651 |
+
else: # That's a basic type
|
| 652 |
+
# Integrate namespace if necessary
|
| 653 |
+
local_node = _create_xml_node(xml_name, xml_prefix, xml_ns)
|
| 654 |
+
local_node.text = unicode_str(new_attr)
|
| 655 |
+
serialized.append(local_node) # type: ignore
|
| 656 |
+
else: # JSON
|
| 657 |
+
for k in reversed(keys): # type: ignore
|
| 658 |
+
new_attr = {k: new_attr}
|
| 659 |
+
|
| 660 |
+
_new_attr = new_attr
|
| 661 |
+
_serialized = serialized
|
| 662 |
+
for k in keys: # type: ignore
|
| 663 |
+
if k not in _serialized:
|
| 664 |
+
_serialized.update(_new_attr) # type: ignore
|
| 665 |
+
_new_attr = _new_attr[k] # type: ignore
|
| 666 |
+
_serialized = _serialized[k]
|
| 667 |
+
except ValueError:
|
| 668 |
+
continue
|
| 669 |
+
|
| 670 |
+
except (AttributeError, KeyError, TypeError) as err:
|
| 671 |
+
msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj))
|
| 672 |
+
raise_with_traceback(SerializationError, msg, err)
|
| 673 |
+
else:
|
| 674 |
+
return serialized
|
| 675 |
+
|
| 676 |
+
def body(self, data, data_type, **kwargs):
|
| 677 |
+
"""Serialize data intended for a request body.
|
| 678 |
+
|
| 679 |
+
:param data: The data to be serialized.
|
| 680 |
+
:param str data_type: The type to be serialized from.
|
| 681 |
+
:rtype: dict
|
| 682 |
+
:raises: SerializationError if serialization fails.
|
| 683 |
+
:raises: ValueError if data is None
|
| 684 |
+
"""
|
| 685 |
+
|
| 686 |
+
# Just in case this is a dict
|
| 687 |
+
internal_data_type_str = data_type.strip("[]{}")
|
| 688 |
+
internal_data_type = self.dependencies.get(internal_data_type_str, None)
|
| 689 |
+
try:
|
| 690 |
+
is_xml_model_serialization = kwargs["is_xml"]
|
| 691 |
+
except KeyError:
|
| 692 |
+
if internal_data_type and issubclass(internal_data_type, Model):
|
| 693 |
+
is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model())
|
| 694 |
+
else:
|
| 695 |
+
is_xml_model_serialization = False
|
| 696 |
+
if internal_data_type and not isinstance(internal_data_type, Enum):
|
| 697 |
+
try:
|
| 698 |
+
deserializer = Deserializer(self.dependencies)
|
| 699 |
+
# Since it's on serialization, it's almost sure that format is not JSON REST
|
| 700 |
+
# We're not able to deal with additional properties for now.
|
| 701 |
+
deserializer.additional_properties_detection = False
|
| 702 |
+
if is_xml_model_serialization:
|
| 703 |
+
deserializer.key_extractors = [ # type: ignore
|
| 704 |
+
attribute_key_case_insensitive_extractor,
|
| 705 |
+
]
|
| 706 |
+
else:
|
| 707 |
+
deserializer.key_extractors = [
|
| 708 |
+
rest_key_case_insensitive_extractor,
|
| 709 |
+
attribute_key_case_insensitive_extractor,
|
| 710 |
+
last_rest_key_case_insensitive_extractor,
|
| 711 |
+
]
|
| 712 |
+
data = deserializer._deserialize(data_type, data)
|
| 713 |
+
except DeserializationError as err:
|
| 714 |
+
raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err)
|
| 715 |
+
|
| 716 |
+
return self._serialize(data, data_type, **kwargs)
|
| 717 |
+
|
| 718 |
+
def url(self, name, data, data_type, **kwargs):
|
| 719 |
+
"""Serialize data intended for a URL path.
|
| 720 |
+
|
| 721 |
+
:param data: The data to be serialized.
|
| 722 |
+
:param str data_type: The type to be serialized from.
|
| 723 |
+
:rtype: str
|
| 724 |
+
:raises: TypeError if serialization fails.
|
| 725 |
+
:raises: ValueError if data is None
|
| 726 |
+
"""
|
| 727 |
+
try:
|
| 728 |
+
output = self.serialize_data(data, data_type, **kwargs)
|
| 729 |
+
if data_type == "bool":
|
| 730 |
+
output = json.dumps(output)
|
| 731 |
+
|
| 732 |
+
if kwargs.get("skip_quote") is True:
|
| 733 |
+
output = str(output)
|
| 734 |
+
else:
|
| 735 |
+
output = quote(str(output), safe="")
|
| 736 |
+
except SerializationError:
|
| 737 |
+
raise TypeError("{} must be type {}.".format(name, data_type))
|
| 738 |
+
else:
|
| 739 |
+
return output
|
| 740 |
+
|
| 741 |
+
def query(self, name, data, data_type, **kwargs):
|
| 742 |
+
"""Serialize data intended for a URL query.
|
| 743 |
+
|
| 744 |
+
:param data: The data to be serialized.
|
| 745 |
+
:param str data_type: The type to be serialized from.
|
| 746 |
+
:rtype: str
|
| 747 |
+
:raises: TypeError if serialization fails.
|
| 748 |
+
:raises: ValueError if data is None
|
| 749 |
+
"""
|
| 750 |
+
try:
|
| 751 |
+
# Treat the list aside, since we don't want to encode the div separator
|
| 752 |
+
if data_type.startswith("["):
|
| 753 |
+
internal_data_type = data_type[1:-1]
|
| 754 |
+
data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data]
|
| 755 |
+
if not kwargs.get("skip_quote", False):
|
| 756 |
+
data = [quote(str(d), safe="") for d in data]
|
| 757 |
+
return str(self.serialize_iter(data, internal_data_type, **kwargs))
|
| 758 |
+
|
| 759 |
+
# Not a list, regular serialization
|
| 760 |
+
output = self.serialize_data(data, data_type, **kwargs)
|
| 761 |
+
if data_type == "bool":
|
| 762 |
+
output = json.dumps(output)
|
| 763 |
+
if kwargs.get("skip_quote") is True:
|
| 764 |
+
output = str(output)
|
| 765 |
+
else:
|
| 766 |
+
output = quote(str(output), safe="")
|
| 767 |
+
except SerializationError:
|
| 768 |
+
raise TypeError("{} must be type {}.".format(name, data_type))
|
| 769 |
+
else:
|
| 770 |
+
return str(output)
|
| 771 |
+
|
| 772 |
+
def header(self, name, data, data_type, **kwargs):
|
| 773 |
+
"""Serialize data intended for a request header.
|
| 774 |
+
|
| 775 |
+
:param data: The data to be serialized.
|
| 776 |
+
:param str data_type: The type to be serialized from.
|
| 777 |
+
:rtype: str
|
| 778 |
+
:raises: TypeError if serialization fails.
|
| 779 |
+
:raises: ValueError if data is None
|
| 780 |
+
"""
|
| 781 |
+
try:
|
| 782 |
+
if data_type in ["[str]"]:
|
| 783 |
+
data = ["" if d is None else d for d in data]
|
| 784 |
+
|
| 785 |
+
output = self.serialize_data(data, data_type, **kwargs)
|
| 786 |
+
if data_type == "bool":
|
| 787 |
+
output = json.dumps(output)
|
| 788 |
+
except SerializationError:
|
| 789 |
+
raise TypeError("{} must be type {}.".format(name, data_type))
|
| 790 |
+
else:
|
| 791 |
+
return str(output)
|
| 792 |
+
|
| 793 |
+
def serialize_data(self, data, data_type, **kwargs):
|
| 794 |
+
"""Serialize generic data according to supplied data type.
|
| 795 |
+
|
| 796 |
+
:param data: The data to be serialized.
|
| 797 |
+
:param str data_type: The type to be serialized from.
|
| 798 |
+
:param bool required: Whether it's essential that the data not be
|
| 799 |
+
empty or None
|
| 800 |
+
:raises: AttributeError if required data is None.
|
| 801 |
+
:raises: ValueError if data is None
|
| 802 |
+
:raises: SerializationError if serialization fails.
|
| 803 |
+
"""
|
| 804 |
+
if data is None:
|
| 805 |
+
raise ValueError("No value for given attribute")
|
| 806 |
+
|
| 807 |
+
try:
|
| 808 |
+
if data is AzureCoreNull:
|
| 809 |
+
return None
|
| 810 |
+
if data_type in self.basic_types.values():
|
| 811 |
+
return self.serialize_basic(data, data_type, **kwargs)
|
| 812 |
+
|
| 813 |
+
elif data_type in self.serialize_type:
|
| 814 |
+
return self.serialize_type[data_type](data, **kwargs)
|
| 815 |
+
|
| 816 |
+
# If dependencies is empty, try with current data class
|
| 817 |
+
# It has to be a subclass of Enum anyway
|
| 818 |
+
enum_type = self.dependencies.get(data_type, data.__class__)
|
| 819 |
+
if issubclass(enum_type, Enum):
|
| 820 |
+
return Serializer.serialize_enum(data, enum_obj=enum_type)
|
| 821 |
+
|
| 822 |
+
iter_type = data_type[0] + data_type[-1]
|
| 823 |
+
if iter_type in self.serialize_type:
|
| 824 |
+
return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs)
|
| 825 |
+
|
| 826 |
+
except (ValueError, TypeError) as err:
|
| 827 |
+
msg = "Unable to serialize value: {!r} as type: {!r}."
|
| 828 |
+
raise_with_traceback(SerializationError, msg.format(data, data_type), err)
|
| 829 |
+
else:
|
| 830 |
+
return self._serialize(data, **kwargs)
|
| 831 |
+
|
| 832 |
+
@classmethod
|
| 833 |
+
def _get_custom_serializers(cls, data_type, **kwargs):
|
| 834 |
+
custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type)
|
| 835 |
+
if custom_serializer:
|
| 836 |
+
return custom_serializer
|
| 837 |
+
if kwargs.get("is_xml", False):
|
| 838 |
+
return cls._xml_basic_types_serializers.get(data_type)
|
| 839 |
+
|
| 840 |
+
@classmethod
|
| 841 |
+
def serialize_basic(cls, data, data_type, **kwargs):
|
| 842 |
+
"""Serialize basic builting data type.
|
| 843 |
+
Serializes objects to str, int, float or bool.
|
| 844 |
+
|
| 845 |
+
Possible kwargs:
|
| 846 |
+
- basic_types_serializers dict[str, callable] : If set, use the callable as serializer
|
| 847 |
+
- is_xml bool : If set, use xml_basic_types_serializers
|
| 848 |
+
|
| 849 |
+
:param data: Object to be serialized.
|
| 850 |
+
:param str data_type: Type of object in the iterable.
|
| 851 |
+
"""
|
| 852 |
+
custom_serializer = cls._get_custom_serializers(data_type, **kwargs)
|
| 853 |
+
if custom_serializer:
|
| 854 |
+
return custom_serializer(data)
|
| 855 |
+
if data_type == "str":
|
| 856 |
+
return cls.serialize_unicode(data)
|
| 857 |
+
return eval(data_type)(data) # nosec
|
| 858 |
+
|
| 859 |
+
@classmethod
|
| 860 |
+
def serialize_unicode(cls, data):
|
| 861 |
+
"""Special handling for serializing unicode strings in Py2.
|
| 862 |
+
Encode to UTF-8 if unicode, otherwise handle as a str.
|
| 863 |
+
|
| 864 |
+
:param data: Object to be serialized.
|
| 865 |
+
:rtype: str
|
| 866 |
+
"""
|
| 867 |
+
try: # If I received an enum, return its value
|
| 868 |
+
return data.value
|
| 869 |
+
except AttributeError:
|
| 870 |
+
pass
|
| 871 |
+
|
| 872 |
+
try:
|
| 873 |
+
if isinstance(data, unicode): # type: ignore
|
| 874 |
+
# Don't change it, JSON and XML ElementTree are totally able
|
| 875 |
+
# to serialize correctly u'' strings
|
| 876 |
+
return data
|
| 877 |
+
except NameError:
|
| 878 |
+
return str(data)
|
| 879 |
+
else:
|
| 880 |
+
return str(data)
|
| 881 |
+
|
| 882 |
+
def serialize_iter(self, data, iter_type, div=None, **kwargs):
|
| 883 |
+
"""Serialize iterable.
|
| 884 |
+
|
| 885 |
+
Supported kwargs:
|
| 886 |
+
- serialization_ctxt dict : The current entry of _attribute_map, or same format.
|
| 887 |
+
serialization_ctxt['type'] should be same as data_type.
|
| 888 |
+
- is_xml bool : If set, serialize as XML
|
| 889 |
+
|
| 890 |
+
:param list attr: Object to be serialized.
|
| 891 |
+
:param str iter_type: Type of object in the iterable.
|
| 892 |
+
:param bool required: Whether the objects in the iterable must
|
| 893 |
+
not be None or empty.
|
| 894 |
+
:param str div: If set, this str will be used to combine the elements
|
| 895 |
+
in the iterable into a combined string. Default is 'None'.
|
| 896 |
+
:rtype: list, str
|
| 897 |
+
"""
|
| 898 |
+
if isinstance(data, str):
|
| 899 |
+
raise SerializationError("Refuse str type as a valid iter type.")
|
| 900 |
+
|
| 901 |
+
serialization_ctxt = kwargs.get("serialization_ctxt", {})
|
| 902 |
+
is_xml = kwargs.get("is_xml", False)
|
| 903 |
+
|
| 904 |
+
serialized = []
|
| 905 |
+
for d in data:
|
| 906 |
+
try:
|
| 907 |
+
serialized.append(self.serialize_data(d, iter_type, **kwargs))
|
| 908 |
+
except ValueError:
|
| 909 |
+
serialized.append(None)
|
| 910 |
+
|
| 911 |
+
if div:
|
| 912 |
+
serialized = ["" if s is None else str(s) for s in serialized]
|
| 913 |
+
serialized = div.join(serialized)
|
| 914 |
+
|
| 915 |
+
if "xml" in serialization_ctxt or is_xml:
|
| 916 |
+
# XML serialization is more complicated
|
| 917 |
+
xml_desc = serialization_ctxt.get("xml", {})
|
| 918 |
+
xml_name = xml_desc.get("name")
|
| 919 |
+
if not xml_name:
|
| 920 |
+
xml_name = serialization_ctxt["key"]
|
| 921 |
+
|
| 922 |
+
# Create a wrap node if necessary (use the fact that Element and list have "append")
|
| 923 |
+
is_wrapped = xml_desc.get("wrapped", False)
|
| 924 |
+
node_name = xml_desc.get("itemsName", xml_name)
|
| 925 |
+
if is_wrapped:
|
| 926 |
+
final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
|
| 927 |
+
else:
|
| 928 |
+
final_result = []
|
| 929 |
+
# All list elements to "local_node"
|
| 930 |
+
for el in serialized:
|
| 931 |
+
if isinstance(el, ET.Element):
|
| 932 |
+
el_node = el
|
| 933 |
+
else:
|
| 934 |
+
el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
|
| 935 |
+
if el is not None: # Otherwise it writes "None" :-p
|
| 936 |
+
el_node.text = str(el)
|
| 937 |
+
final_result.append(el_node)
|
| 938 |
+
return final_result
|
| 939 |
+
return serialized
|
| 940 |
+
|
| 941 |
+
def serialize_dict(self, attr, dict_type, **kwargs):
|
| 942 |
+
"""Serialize a dictionary of objects.
|
| 943 |
+
|
| 944 |
+
:param dict attr: Object to be serialized.
|
| 945 |
+
:param str dict_type: Type of object in the dictionary.
|
| 946 |
+
:param bool required: Whether the objects in the dictionary must
|
| 947 |
+
not be None or empty.
|
| 948 |
+
:rtype: dict
|
| 949 |
+
"""
|
| 950 |
+
serialization_ctxt = kwargs.get("serialization_ctxt", {})
|
| 951 |
+
serialized = {}
|
| 952 |
+
for key, value in attr.items():
|
| 953 |
+
try:
|
| 954 |
+
serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs)
|
| 955 |
+
except ValueError:
|
| 956 |
+
serialized[self.serialize_unicode(key)] = None
|
| 957 |
+
|
| 958 |
+
if "xml" in serialization_ctxt:
|
| 959 |
+
# XML serialization is more complicated
|
| 960 |
+
xml_desc = serialization_ctxt["xml"]
|
| 961 |
+
xml_name = xml_desc["name"]
|
| 962 |
+
|
| 963 |
+
final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None))
|
| 964 |
+
for key, value in serialized.items():
|
| 965 |
+
ET.SubElement(final_result, key).text = value
|
| 966 |
+
return final_result
|
| 967 |
+
|
| 968 |
+
return serialized
|
| 969 |
+
|
| 970 |
+
def serialize_object(self, attr, **kwargs):
|
| 971 |
+
"""Serialize a generic object.
|
| 972 |
+
This will be handled as a dictionary. If object passed in is not
|
| 973 |
+
a basic type (str, int, float, dict, list) it will simply be
|
| 974 |
+
cast to str.
|
| 975 |
+
|
| 976 |
+
:param dict attr: Object to be serialized.
|
| 977 |
+
:rtype: dict or str
|
| 978 |
+
"""
|
| 979 |
+
if attr is None:
|
| 980 |
+
return None
|
| 981 |
+
if isinstance(attr, ET.Element):
|
| 982 |
+
return attr
|
| 983 |
+
obj_type = type(attr)
|
| 984 |
+
if obj_type in self.basic_types:
|
| 985 |
+
return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs)
|
| 986 |
+
if obj_type is _long_type:
|
| 987 |
+
return self.serialize_long(attr)
|
| 988 |
+
if obj_type is unicode_str:
|
| 989 |
+
return self.serialize_unicode(attr)
|
| 990 |
+
if obj_type is datetime.datetime:
|
| 991 |
+
return self.serialize_iso(attr)
|
| 992 |
+
if obj_type is datetime.date:
|
| 993 |
+
return self.serialize_date(attr)
|
| 994 |
+
if obj_type is datetime.time:
|
| 995 |
+
return self.serialize_time(attr)
|
| 996 |
+
if obj_type is datetime.timedelta:
|
| 997 |
+
return self.serialize_duration(attr)
|
| 998 |
+
if obj_type is decimal.Decimal:
|
| 999 |
+
return self.serialize_decimal(attr)
|
| 1000 |
+
|
| 1001 |
+
# If it's a model or I know this dependency, serialize as a Model
|
| 1002 |
+
elif obj_type in self.dependencies.values() or isinstance(attr, Model):
|
| 1003 |
+
return self._serialize(attr)
|
| 1004 |
+
|
| 1005 |
+
if obj_type == dict:
|
| 1006 |
+
serialized = {}
|
| 1007 |
+
for key, value in attr.items():
|
| 1008 |
+
try:
|
| 1009 |
+
serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs)
|
| 1010 |
+
except ValueError:
|
| 1011 |
+
serialized[self.serialize_unicode(key)] = None
|
| 1012 |
+
return serialized
|
| 1013 |
+
|
| 1014 |
+
if obj_type == list:
|
| 1015 |
+
serialized = []
|
| 1016 |
+
for obj in attr:
|
| 1017 |
+
try:
|
| 1018 |
+
serialized.append(self.serialize_object(obj, **kwargs))
|
| 1019 |
+
except ValueError:
|
| 1020 |
+
pass
|
| 1021 |
+
return serialized
|
| 1022 |
+
return str(attr)
|
| 1023 |
+
|
| 1024 |
+
@staticmethod
|
| 1025 |
+
def serialize_enum(attr, enum_obj=None):
|
| 1026 |
+
try:
|
| 1027 |
+
result = attr.value
|
| 1028 |
+
except AttributeError:
|
| 1029 |
+
result = attr
|
| 1030 |
+
try:
|
| 1031 |
+
enum_obj(result) # type: ignore
|
| 1032 |
+
return result
|
| 1033 |
+
except ValueError:
|
| 1034 |
+
for enum_value in enum_obj: # type: ignore
|
| 1035 |
+
if enum_value.value.lower() == str(attr).lower():
|
| 1036 |
+
return enum_value.value
|
| 1037 |
+
error = "{!r} is not valid value for enum {!r}"
|
| 1038 |
+
raise SerializationError(error.format(attr, enum_obj))
|
| 1039 |
+
|
| 1040 |
+
@staticmethod
|
| 1041 |
+
def serialize_bytearray(attr, **kwargs):
|
| 1042 |
+
"""Serialize bytearray into base-64 string.
|
| 1043 |
+
|
| 1044 |
+
:param attr: Object to be serialized.
|
| 1045 |
+
:rtype: str
|
| 1046 |
+
"""
|
| 1047 |
+
return b64encode(attr).decode()
|
| 1048 |
+
|
| 1049 |
+
@staticmethod
|
| 1050 |
+
def serialize_base64(attr, **kwargs):
|
| 1051 |
+
"""Serialize str into base-64 string.
|
| 1052 |
+
|
| 1053 |
+
:param attr: Object to be serialized.
|
| 1054 |
+
:rtype: str
|
| 1055 |
+
"""
|
| 1056 |
+
encoded = b64encode(attr).decode("ascii")
|
| 1057 |
+
return encoded.strip("=").replace("+", "-").replace("/", "_")
|
| 1058 |
+
|
| 1059 |
+
@staticmethod
|
| 1060 |
+
def serialize_decimal(attr, **kwargs):
|
| 1061 |
+
"""Serialize Decimal object to float.
|
| 1062 |
+
|
| 1063 |
+
:param attr: Object to be serialized.
|
| 1064 |
+
:rtype: float
|
| 1065 |
+
"""
|
| 1066 |
+
return float(attr)
|
| 1067 |
+
|
| 1068 |
+
@staticmethod
|
| 1069 |
+
def serialize_long(attr, **kwargs):
|
| 1070 |
+
"""Serialize long (Py2) or int (Py3).
|
| 1071 |
+
|
| 1072 |
+
:param attr: Object to be serialized.
|
| 1073 |
+
:rtype: int/long
|
| 1074 |
+
"""
|
| 1075 |
+
return _long_type(attr)
|
| 1076 |
+
|
| 1077 |
+
@staticmethod
|
| 1078 |
+
def serialize_date(attr, **kwargs):
|
| 1079 |
+
"""Serialize Date object into ISO-8601 formatted string.
|
| 1080 |
+
|
| 1081 |
+
:param Date attr: Object to be serialized.
|
| 1082 |
+
:rtype: str
|
| 1083 |
+
"""
|
| 1084 |
+
if isinstance(attr, str):
|
| 1085 |
+
attr = isodate.parse_date(attr)
|
| 1086 |
+
t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day)
|
| 1087 |
+
return t
|
| 1088 |
+
|
| 1089 |
+
@staticmethod
|
| 1090 |
+
def serialize_time(attr, **kwargs):
|
| 1091 |
+
"""Serialize Time object into ISO-8601 formatted string.
|
| 1092 |
+
|
| 1093 |
+
:param datetime.time attr: Object to be serialized.
|
| 1094 |
+
:rtype: str
|
| 1095 |
+
"""
|
| 1096 |
+
if isinstance(attr, str):
|
| 1097 |
+
attr = isodate.parse_time(attr)
|
| 1098 |
+
t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second)
|
| 1099 |
+
if attr.microsecond:
|
| 1100 |
+
t += ".{:02}".format(attr.microsecond)
|
| 1101 |
+
return t
|
| 1102 |
+
|
| 1103 |
+
@staticmethod
|
| 1104 |
+
def serialize_duration(attr, **kwargs):
|
| 1105 |
+
"""Serialize TimeDelta object into ISO-8601 formatted string.
|
| 1106 |
+
|
| 1107 |
+
:param TimeDelta attr: Object to be serialized.
|
| 1108 |
+
:rtype: str
|
| 1109 |
+
"""
|
| 1110 |
+
if isinstance(attr, str):
|
| 1111 |
+
attr = isodate.parse_duration(attr)
|
| 1112 |
+
return isodate.duration_isoformat(attr)
|
| 1113 |
+
|
| 1114 |
+
@staticmethod
|
| 1115 |
+
def serialize_rfc(attr, **kwargs):
|
| 1116 |
+
"""Serialize Datetime object into RFC-1123 formatted string.
|
| 1117 |
+
|
| 1118 |
+
:param Datetime attr: Object to be serialized.
|
| 1119 |
+
:rtype: str
|
| 1120 |
+
:raises: TypeError if format invalid.
|
| 1121 |
+
"""
|
| 1122 |
+
try:
|
| 1123 |
+
if not attr.tzinfo:
|
| 1124 |
+
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
|
| 1125 |
+
utc = attr.utctimetuple()
|
| 1126 |
+
except AttributeError:
|
| 1127 |
+
raise TypeError("RFC1123 object must be valid Datetime object.")
|
| 1128 |
+
|
| 1129 |
+
return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format(
|
| 1130 |
+
Serializer.days[utc.tm_wday],
|
| 1131 |
+
utc.tm_mday,
|
| 1132 |
+
Serializer.months[utc.tm_mon],
|
| 1133 |
+
utc.tm_year,
|
| 1134 |
+
utc.tm_hour,
|
| 1135 |
+
utc.tm_min,
|
| 1136 |
+
utc.tm_sec,
|
| 1137 |
+
)
|
| 1138 |
+
|
| 1139 |
+
@staticmethod
|
| 1140 |
+
def serialize_iso(attr, **kwargs):
|
| 1141 |
+
"""Serialize Datetime object into ISO-8601 formatted string.
|
| 1142 |
+
|
| 1143 |
+
:param Datetime attr: Object to be serialized.
|
| 1144 |
+
:rtype: str
|
| 1145 |
+
:raises: SerializationError if format invalid.
|
| 1146 |
+
"""
|
| 1147 |
+
if isinstance(attr, str):
|
| 1148 |
+
attr = isodate.parse_datetime(attr)
|
| 1149 |
+
try:
|
| 1150 |
+
if not attr.tzinfo:
|
| 1151 |
+
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
|
| 1152 |
+
utc = attr.utctimetuple()
|
| 1153 |
+
if utc.tm_year > 9999 or utc.tm_year < 1:
|
| 1154 |
+
raise OverflowError("Hit max or min date")
|
| 1155 |
+
|
| 1156 |
+
microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0")
|
| 1157 |
+
if microseconds:
|
| 1158 |
+
microseconds = "." + microseconds
|
| 1159 |
+
date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format(
|
| 1160 |
+
utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec
|
| 1161 |
+
)
|
| 1162 |
+
return date + microseconds + "Z"
|
| 1163 |
+
except (ValueError, OverflowError) as err:
|
| 1164 |
+
msg = "Unable to serialize datetime object."
|
| 1165 |
+
raise_with_traceback(SerializationError, msg, err)
|
| 1166 |
+
except AttributeError as err:
|
| 1167 |
+
msg = "ISO-8601 object must be valid Datetime object."
|
| 1168 |
+
raise_with_traceback(TypeError, msg, err)
|
| 1169 |
+
|
| 1170 |
+
@staticmethod
|
| 1171 |
+
def serialize_unix(attr, **kwargs):
|
| 1172 |
+
"""Serialize Datetime object into IntTime format.
|
| 1173 |
+
This is represented as seconds.
|
| 1174 |
+
|
| 1175 |
+
:param Datetime attr: Object to be serialized.
|
| 1176 |
+
:rtype: int
|
| 1177 |
+
:raises: SerializationError if format invalid
|
| 1178 |
+
"""
|
| 1179 |
+
if isinstance(attr, int):
|
| 1180 |
+
return attr
|
| 1181 |
+
try:
|
| 1182 |
+
if not attr.tzinfo:
|
| 1183 |
+
_LOGGER.warning("Datetime with no tzinfo will be considered UTC.")
|
| 1184 |
+
return int(calendar.timegm(attr.utctimetuple()))
|
| 1185 |
+
except AttributeError:
|
| 1186 |
+
raise TypeError("Unix time object must be valid Datetime object.")
|
| 1187 |
+
|
| 1188 |
+
|
| 1189 |
+
def rest_key_extractor(attr, attr_desc, data):
|
| 1190 |
+
key = attr_desc["key"]
|
| 1191 |
+
working_data = data
|
| 1192 |
+
|
| 1193 |
+
while "." in key:
|
| 1194 |
+
# Need the cast, as for some reasons "split" is typed as list[str | Any]
|
| 1195 |
+
dict_keys = cast(List[str], _FLATTEN.split(key))
|
| 1196 |
+
if len(dict_keys) == 1:
|
| 1197 |
+
key = _decode_attribute_map_key(dict_keys[0])
|
| 1198 |
+
break
|
| 1199 |
+
working_key = _decode_attribute_map_key(dict_keys[0])
|
| 1200 |
+
working_data = working_data.get(working_key, data)
|
| 1201 |
+
if working_data is None:
|
| 1202 |
+
# If at any point while following flatten JSON path see None, it means
|
| 1203 |
+
# that all properties under are None as well
|
| 1204 |
+
# https://github.com/Azure/msrest-for-python/issues/197
|
| 1205 |
+
return None
|
| 1206 |
+
key = ".".join(dict_keys[1:])
|
| 1207 |
+
|
| 1208 |
+
return working_data.get(key)
|
| 1209 |
+
|
| 1210 |
+
|
| 1211 |
+
def rest_key_case_insensitive_extractor(attr, attr_desc, data):
|
| 1212 |
+
key = attr_desc["key"]
|
| 1213 |
+
working_data = data
|
| 1214 |
+
|
| 1215 |
+
while "." in key:
|
| 1216 |
+
dict_keys = _FLATTEN.split(key)
|
| 1217 |
+
if len(dict_keys) == 1:
|
| 1218 |
+
key = _decode_attribute_map_key(dict_keys[0])
|
| 1219 |
+
break
|
| 1220 |
+
working_key = _decode_attribute_map_key(dict_keys[0])
|
| 1221 |
+
working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data)
|
| 1222 |
+
if working_data is None:
|
| 1223 |
+
# If at any point while following flatten JSON path see None, it means
|
| 1224 |
+
# that all properties under are None as well
|
| 1225 |
+
# https://github.com/Azure/msrest-for-python/issues/197
|
| 1226 |
+
return None
|
| 1227 |
+
key = ".".join(dict_keys[1:])
|
| 1228 |
+
|
| 1229 |
+
if working_data:
|
| 1230 |
+
return attribute_key_case_insensitive_extractor(key, None, working_data)
|
| 1231 |
+
|
| 1232 |
+
|
| 1233 |
+
def last_rest_key_extractor(attr, attr_desc, data):
|
| 1234 |
+
"""Extract the attribute in "data" based on the last part of the JSON path key."""
|
| 1235 |
+
key = attr_desc["key"]
|
| 1236 |
+
dict_keys = _FLATTEN.split(key)
|
| 1237 |
+
return attribute_key_extractor(dict_keys[-1], None, data)
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
def last_rest_key_case_insensitive_extractor(attr, attr_desc, data):
|
| 1241 |
+
"""Extract the attribute in "data" based on the last part of the JSON path key.
|
| 1242 |
+
|
| 1243 |
+
This is the case insensitive version of "last_rest_key_extractor"
|
| 1244 |
+
"""
|
| 1245 |
+
key = attr_desc["key"]
|
| 1246 |
+
dict_keys = _FLATTEN.split(key)
|
| 1247 |
+
return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data)
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
def attribute_key_extractor(attr, _, data):
|
| 1251 |
+
return data.get(attr)
|
| 1252 |
+
|
| 1253 |
+
|
| 1254 |
+
def attribute_key_case_insensitive_extractor(attr, _, data):
|
| 1255 |
+
found_key = None
|
| 1256 |
+
lower_attr = attr.lower()
|
| 1257 |
+
for key in data:
|
| 1258 |
+
if lower_attr == key.lower():
|
| 1259 |
+
found_key = key
|
| 1260 |
+
break
|
| 1261 |
+
|
| 1262 |
+
return data.get(found_key)
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
def _extract_name_from_internal_type(internal_type):
|
| 1266 |
+
"""Given an internal type XML description, extract correct XML name with namespace.
|
| 1267 |
+
|
| 1268 |
+
:param dict internal_type: An model type
|
| 1269 |
+
:rtype: tuple
|
| 1270 |
+
:returns: A tuple XML name + namespace dict
|
| 1271 |
+
"""
|
| 1272 |
+
internal_type_xml_map = getattr(internal_type, "_xml_map", {})
|
| 1273 |
+
xml_name = internal_type_xml_map.get("name", internal_type.__name__)
|
| 1274 |
+
xml_ns = internal_type_xml_map.get("ns", None)
|
| 1275 |
+
if xml_ns:
|
| 1276 |
+
xml_name = "{}{}".format(xml_ns, xml_name)
|
| 1277 |
+
return xml_name
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
def xml_key_extractor(attr, attr_desc, data):
|
| 1281 |
+
if isinstance(data, dict):
|
| 1282 |
+
return None
|
| 1283 |
+
|
| 1284 |
+
# Test if this model is XML ready first
|
| 1285 |
+
if not isinstance(data, ET.Element):
|
| 1286 |
+
return None
|
| 1287 |
+
|
| 1288 |
+
xml_desc = attr_desc.get("xml", {})
|
| 1289 |
+
xml_name = xml_desc.get("name", attr_desc["key"])
|
| 1290 |
+
|
| 1291 |
+
# Look for a children
|
| 1292 |
+
is_iter_type = attr_desc["type"].startswith("[")
|
| 1293 |
+
is_wrapped = xml_desc.get("wrapped", False)
|
| 1294 |
+
internal_type = attr_desc.get("internalType", None)
|
| 1295 |
+
internal_type_xml_map = getattr(internal_type, "_xml_map", {})
|
| 1296 |
+
|
| 1297 |
+
# Integrate namespace if necessary
|
| 1298 |
+
xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None))
|
| 1299 |
+
if xml_ns:
|
| 1300 |
+
xml_name = "{}{}".format(xml_ns, xml_name)
|
| 1301 |
+
|
| 1302 |
+
# If it's an attribute, that's simple
|
| 1303 |
+
if xml_desc.get("attr", False):
|
| 1304 |
+
return data.get(xml_name)
|
| 1305 |
+
|
| 1306 |
+
# If it's x-ms-text, that's simple too
|
| 1307 |
+
if xml_desc.get("text", False):
|
| 1308 |
+
return data.text
|
| 1309 |
+
|
| 1310 |
+
# Scenario where I take the local name:
|
| 1311 |
+
# - Wrapped node
|
| 1312 |
+
# - Internal type is an enum (considered basic types)
|
| 1313 |
+
# - Internal type has no XML/Name node
|
| 1314 |
+
if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)):
|
| 1315 |
+
children = data.findall(xml_name)
|
| 1316 |
+
# If internal type has a local name and it's not a list, I use that name
|
| 1317 |
+
elif not is_iter_type and internal_type and "name" in internal_type_xml_map:
|
| 1318 |
+
xml_name = _extract_name_from_internal_type(internal_type)
|
| 1319 |
+
children = data.findall(xml_name)
|
| 1320 |
+
# That's an array
|
| 1321 |
+
else:
|
| 1322 |
+
if internal_type: # Complex type, ignore itemsName and use the complex type name
|
| 1323 |
+
items_name = _extract_name_from_internal_type(internal_type)
|
| 1324 |
+
else:
|
| 1325 |
+
items_name = xml_desc.get("itemsName", xml_name)
|
| 1326 |
+
children = data.findall(items_name)
|
| 1327 |
+
|
| 1328 |
+
if len(children) == 0:
|
| 1329 |
+
if is_iter_type:
|
| 1330 |
+
if is_wrapped:
|
| 1331 |
+
return None # is_wrapped no node, we want None
|
| 1332 |
+
else:
|
| 1333 |
+
return [] # not wrapped, assume empty list
|
| 1334 |
+
return None # Assume it's not there, maybe an optional node.
|
| 1335 |
+
|
| 1336 |
+
# If is_iter_type and not wrapped, return all found children
|
| 1337 |
+
if is_iter_type:
|
| 1338 |
+
if not is_wrapped:
|
| 1339 |
+
return children
|
| 1340 |
+
else: # Iter and wrapped, should have found one node only (the wrap one)
|
| 1341 |
+
if len(children) != 1:
|
| 1342 |
+
raise DeserializationError(
|
| 1343 |
+
"Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format(
|
| 1344 |
+
xml_name
|
| 1345 |
+
)
|
| 1346 |
+
)
|
| 1347 |
+
return list(children[0]) # Might be empty list and that's ok.
|
| 1348 |
+
|
| 1349 |
+
# Here it's not a itertype, we should have found one element only or empty
|
| 1350 |
+
if len(children) > 1:
|
| 1351 |
+
raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name))
|
| 1352 |
+
return children[0]
|
| 1353 |
+
|
| 1354 |
+
|
| 1355 |
+
class Deserializer(object):
|
| 1356 |
+
"""Response object model deserializer.
|
| 1357 |
+
|
| 1358 |
+
:param dict classes: Class type dictionary for deserializing complex types.
|
| 1359 |
+
:ivar list key_extractors: Ordered list of extractors to be used by this deserializer.
|
| 1360 |
+
"""
|
| 1361 |
+
|
| 1362 |
+
basic_types = {str: "str", int: "int", bool: "bool", float: "float"}
|
| 1363 |
+
|
| 1364 |
+
valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?")
|
| 1365 |
+
|
| 1366 |
+
def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]]=None):
|
| 1367 |
+
self.deserialize_type = {
|
| 1368 |
+
"iso-8601": Deserializer.deserialize_iso,
|
| 1369 |
+
"rfc-1123": Deserializer.deserialize_rfc,
|
| 1370 |
+
"unix-time": Deserializer.deserialize_unix,
|
| 1371 |
+
"duration": Deserializer.deserialize_duration,
|
| 1372 |
+
"date": Deserializer.deserialize_date,
|
| 1373 |
+
"time": Deserializer.deserialize_time,
|
| 1374 |
+
"decimal": Deserializer.deserialize_decimal,
|
| 1375 |
+
"long": Deserializer.deserialize_long,
|
| 1376 |
+
"bytearray": Deserializer.deserialize_bytearray,
|
| 1377 |
+
"base64": Deserializer.deserialize_base64,
|
| 1378 |
+
"object": self.deserialize_object,
|
| 1379 |
+
"[]": self.deserialize_iter,
|
| 1380 |
+
"{}": self.deserialize_dict,
|
| 1381 |
+
}
|
| 1382 |
+
self.deserialize_expected_types = {
|
| 1383 |
+
"duration": (isodate.Duration, datetime.timedelta),
|
| 1384 |
+
"iso-8601": (datetime.datetime),
|
| 1385 |
+
}
|
| 1386 |
+
self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {}
|
| 1387 |
+
self.key_extractors = [rest_key_extractor, xml_key_extractor]
|
| 1388 |
+
# Additional properties only works if the "rest_key_extractor" is used to
|
| 1389 |
+
# extract the keys. Making it to work whatever the key extractor is too much
|
| 1390 |
+
# complicated, with no real scenario for now.
|
| 1391 |
+
# So adding a flag to disable additional properties detection. This flag should be
|
| 1392 |
+
# used if your expect the deserialization to NOT come from a JSON REST syntax.
|
| 1393 |
+
# Otherwise, result are unexpected
|
| 1394 |
+
self.additional_properties_detection = True
|
| 1395 |
+
|
| 1396 |
+
def __call__(self, target_obj, response_data, content_type=None):
|
| 1397 |
+
"""Call the deserializer to process a REST response.
|
| 1398 |
+
|
| 1399 |
+
:param str target_obj: Target data type to deserialize to.
|
| 1400 |
+
:param requests.Response response_data: REST response object.
|
| 1401 |
+
:param str content_type: Swagger "produces" if available.
|
| 1402 |
+
:raises: DeserializationError if deserialization fails.
|
| 1403 |
+
:return: Deserialized object.
|
| 1404 |
+
"""
|
| 1405 |
+
data = self._unpack_content(response_data, content_type)
|
| 1406 |
+
return self._deserialize(target_obj, data)
|
| 1407 |
+
|
| 1408 |
+
def _deserialize(self, target_obj, data):
|
| 1409 |
+
"""Call the deserializer on a model.
|
| 1410 |
+
|
| 1411 |
+
Data needs to be already deserialized as JSON or XML ElementTree
|
| 1412 |
+
|
| 1413 |
+
:param str target_obj: Target data type to deserialize to.
|
| 1414 |
+
:param object data: Object to deserialize.
|
| 1415 |
+
:raises: DeserializationError if deserialization fails.
|
| 1416 |
+
:return: Deserialized object.
|
| 1417 |
+
"""
|
| 1418 |
+
# This is already a model, go recursive just in case
|
| 1419 |
+
if hasattr(data, "_attribute_map"):
|
| 1420 |
+
constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")]
|
| 1421 |
+
try:
|
| 1422 |
+
for attr, mapconfig in data._attribute_map.items():
|
| 1423 |
+
if attr in constants:
|
| 1424 |
+
continue
|
| 1425 |
+
value = getattr(data, attr)
|
| 1426 |
+
if value is None:
|
| 1427 |
+
continue
|
| 1428 |
+
local_type = mapconfig["type"]
|
| 1429 |
+
internal_data_type = local_type.strip("[]{}")
|
| 1430 |
+
if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum):
|
| 1431 |
+
continue
|
| 1432 |
+
setattr(data, attr, self._deserialize(local_type, value))
|
| 1433 |
+
return data
|
| 1434 |
+
except AttributeError:
|
| 1435 |
+
return
|
| 1436 |
+
|
| 1437 |
+
response, class_name = self._classify_target(target_obj, data)
|
| 1438 |
+
|
| 1439 |
+
if isinstance(response, basestring):
|
| 1440 |
+
return self.deserialize_data(data, response)
|
| 1441 |
+
elif isinstance(response, type) and issubclass(response, Enum):
|
| 1442 |
+
return self.deserialize_enum(data, response)
|
| 1443 |
+
|
| 1444 |
+
if data is None:
|
| 1445 |
+
return data
|
| 1446 |
+
try:
|
| 1447 |
+
attributes = response._attribute_map # type: ignore
|
| 1448 |
+
d_attrs = {}
|
| 1449 |
+
for attr, attr_desc in attributes.items():
|
| 1450 |
+
# Check empty string. If it's not empty, someone has a real "additionalProperties"...
|
| 1451 |
+
if attr == "additional_properties" and attr_desc["key"] == "":
|
| 1452 |
+
continue
|
| 1453 |
+
raw_value = None
|
| 1454 |
+
# Enhance attr_desc with some dynamic data
|
| 1455 |
+
attr_desc = attr_desc.copy() # Do a copy, do not change the real one
|
| 1456 |
+
internal_data_type = attr_desc["type"].strip("[]{}")
|
| 1457 |
+
if internal_data_type in self.dependencies:
|
| 1458 |
+
attr_desc["internalType"] = self.dependencies[internal_data_type]
|
| 1459 |
+
|
| 1460 |
+
for key_extractor in self.key_extractors:
|
| 1461 |
+
found_value = key_extractor(attr, attr_desc, data)
|
| 1462 |
+
if found_value is not None:
|
| 1463 |
+
if raw_value is not None and raw_value != found_value:
|
| 1464 |
+
msg = (
|
| 1465 |
+
"Ignoring extracted value '%s' from %s for key '%s'"
|
| 1466 |
+
" (duplicate extraction, follow extractors order)"
|
| 1467 |
+
)
|
| 1468 |
+
_LOGGER.warning(msg, found_value, key_extractor, attr)
|
| 1469 |
+
continue
|
| 1470 |
+
raw_value = found_value
|
| 1471 |
+
|
| 1472 |
+
value = self.deserialize_data(raw_value, attr_desc["type"])
|
| 1473 |
+
d_attrs[attr] = value
|
| 1474 |
+
except (AttributeError, TypeError, KeyError) as err:
|
| 1475 |
+
msg = "Unable to deserialize to object: " + class_name # type: ignore
|
| 1476 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1477 |
+
else:
|
| 1478 |
+
additional_properties = self._build_additional_properties(attributes, data)
|
| 1479 |
+
return self._instantiate_model(response, d_attrs, additional_properties)
|
| 1480 |
+
|
| 1481 |
+
def _build_additional_properties(self, attribute_map, data):
|
| 1482 |
+
if not self.additional_properties_detection:
|
| 1483 |
+
return None
|
| 1484 |
+
if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "":
|
| 1485 |
+
# Check empty string. If it's not empty, someone has a real "additionalProperties"
|
| 1486 |
+
return None
|
| 1487 |
+
if isinstance(data, ET.Element):
|
| 1488 |
+
data = {el.tag: el.text for el in data}
|
| 1489 |
+
|
| 1490 |
+
known_keys = {
|
| 1491 |
+
_decode_attribute_map_key(_FLATTEN.split(desc["key"])[0])
|
| 1492 |
+
for desc in attribute_map.values()
|
| 1493 |
+
if desc["key"] != ""
|
| 1494 |
+
}
|
| 1495 |
+
present_keys = set(data.keys())
|
| 1496 |
+
missing_keys = present_keys - known_keys
|
| 1497 |
+
return {key: data[key] for key in missing_keys}
|
| 1498 |
+
|
| 1499 |
+
def _classify_target(self, target, data):
|
| 1500 |
+
"""Check to see whether the deserialization target object can
|
| 1501 |
+
be classified into a subclass.
|
| 1502 |
+
Once classification has been determined, initialize object.
|
| 1503 |
+
|
| 1504 |
+
:param str target: The target object type to deserialize to.
|
| 1505 |
+
:param str/dict data: The response data to deserialize.
|
| 1506 |
+
"""
|
| 1507 |
+
if target is None:
|
| 1508 |
+
return None, None
|
| 1509 |
+
|
| 1510 |
+
if isinstance(target, basestring):
|
| 1511 |
+
try:
|
| 1512 |
+
target = self.dependencies[target]
|
| 1513 |
+
except KeyError:
|
| 1514 |
+
return target, target
|
| 1515 |
+
|
| 1516 |
+
try:
|
| 1517 |
+
target = target._classify(data, self.dependencies)
|
| 1518 |
+
except AttributeError:
|
| 1519 |
+
pass # Target is not a Model, no classify
|
| 1520 |
+
return target, target.__class__.__name__ # type: ignore
|
| 1521 |
+
|
| 1522 |
+
def failsafe_deserialize(self, target_obj, data, content_type=None):
|
| 1523 |
+
"""Ignores any errors encountered in deserialization,
|
| 1524 |
+
and falls back to not deserializing the object. Recommended
|
| 1525 |
+
for use in error deserialization, as we want to return the
|
| 1526 |
+
HttpResponseError to users, and not have them deal with
|
| 1527 |
+
a deserialization error.
|
| 1528 |
+
|
| 1529 |
+
:param str target_obj: The target object type to deserialize to.
|
| 1530 |
+
:param str/dict data: The response data to deserialize.
|
| 1531 |
+
:param str content_type: Swagger "produces" if available.
|
| 1532 |
+
"""
|
| 1533 |
+
try:
|
| 1534 |
+
return self(target_obj, data, content_type=content_type)
|
| 1535 |
+
except:
|
| 1536 |
+
_LOGGER.debug(
|
| 1537 |
+
"Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True
|
| 1538 |
+
)
|
| 1539 |
+
return None
|
| 1540 |
+
|
| 1541 |
+
@staticmethod
|
| 1542 |
+
def _unpack_content(raw_data, content_type=None):
|
| 1543 |
+
"""Extract the correct structure for deserialization.
|
| 1544 |
+
|
| 1545 |
+
If raw_data is a PipelineResponse, try to extract the result of RawDeserializer.
|
| 1546 |
+
if we can't, raise. Your Pipeline should have a RawDeserializer.
|
| 1547 |
+
|
| 1548 |
+
If not a pipeline response and raw_data is bytes or string, use content-type
|
| 1549 |
+
to decode it. If no content-type, try JSON.
|
| 1550 |
+
|
| 1551 |
+
If raw_data is something else, bypass all logic and return it directly.
|
| 1552 |
+
|
| 1553 |
+
:param raw_data: Data to be processed.
|
| 1554 |
+
:param content_type: How to parse if raw_data is a string/bytes.
|
| 1555 |
+
:raises JSONDecodeError: If JSON is requested and parsing is impossible.
|
| 1556 |
+
:raises UnicodeDecodeError: If bytes is not UTF8
|
| 1557 |
+
"""
|
| 1558 |
+
# Assume this is enough to detect a Pipeline Response without importing it
|
| 1559 |
+
context = getattr(raw_data, "context", {})
|
| 1560 |
+
if context:
|
| 1561 |
+
if RawDeserializer.CONTEXT_NAME in context:
|
| 1562 |
+
return context[RawDeserializer.CONTEXT_NAME]
|
| 1563 |
+
raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize")
|
| 1564 |
+
|
| 1565 |
+
# Assume this is enough to recognize universal_http.ClientResponse without importing it
|
| 1566 |
+
if hasattr(raw_data, "body"):
|
| 1567 |
+
return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers)
|
| 1568 |
+
|
| 1569 |
+
# Assume this enough to recognize requests.Response without importing it.
|
| 1570 |
+
if hasattr(raw_data, "_content_consumed"):
|
| 1571 |
+
return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers)
|
| 1572 |
+
|
| 1573 |
+
if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"):
|
| 1574 |
+
return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore
|
| 1575 |
+
return raw_data
|
| 1576 |
+
|
| 1577 |
+
def _instantiate_model(self, response, attrs, additional_properties=None):
|
| 1578 |
+
"""Instantiate a response model passing in deserialized args.
|
| 1579 |
+
|
| 1580 |
+
:param response: The response model class.
|
| 1581 |
+
:param d_attrs: The deserialized response attributes.
|
| 1582 |
+
"""
|
| 1583 |
+
if callable(response):
|
| 1584 |
+
subtype = getattr(response, "_subtype_map", {})
|
| 1585 |
+
try:
|
| 1586 |
+
readonly = [k for k, v in response._validation.items() if v.get("readonly")]
|
| 1587 |
+
const = [k for k, v in response._validation.items() if v.get("constant")]
|
| 1588 |
+
kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const}
|
| 1589 |
+
response_obj = response(**kwargs)
|
| 1590 |
+
for attr in readonly:
|
| 1591 |
+
setattr(response_obj, attr, attrs.get(attr))
|
| 1592 |
+
if additional_properties:
|
| 1593 |
+
response_obj.additional_properties = additional_properties
|
| 1594 |
+
return response_obj
|
| 1595 |
+
except TypeError as err:
|
| 1596 |
+
msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore
|
| 1597 |
+
raise DeserializationError(msg + str(err))
|
| 1598 |
+
else:
|
| 1599 |
+
try:
|
| 1600 |
+
for attr, value in attrs.items():
|
| 1601 |
+
setattr(response, attr, value)
|
| 1602 |
+
return response
|
| 1603 |
+
except Exception as exp:
|
| 1604 |
+
msg = "Unable to populate response model. "
|
| 1605 |
+
msg += "Type: {}, Error: {}".format(type(response), exp)
|
| 1606 |
+
raise DeserializationError(msg)
|
| 1607 |
+
|
| 1608 |
+
def deserialize_data(self, data, data_type):
|
| 1609 |
+
"""Process data for deserialization according to data type.
|
| 1610 |
+
|
| 1611 |
+
:param str data: The response string to be deserialized.
|
| 1612 |
+
:param str data_type: The type to deserialize to.
|
| 1613 |
+
:raises: DeserializationError if deserialization fails.
|
| 1614 |
+
:return: Deserialized object.
|
| 1615 |
+
"""
|
| 1616 |
+
if data is None:
|
| 1617 |
+
return data
|
| 1618 |
+
|
| 1619 |
+
try:
|
| 1620 |
+
if not data_type:
|
| 1621 |
+
return data
|
| 1622 |
+
if data_type in self.basic_types.values():
|
| 1623 |
+
return self.deserialize_basic(data, data_type)
|
| 1624 |
+
if data_type in self.deserialize_type:
|
| 1625 |
+
if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())):
|
| 1626 |
+
return data
|
| 1627 |
+
|
| 1628 |
+
is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"]
|
| 1629 |
+
if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text:
|
| 1630 |
+
return None
|
| 1631 |
+
data_val = self.deserialize_type[data_type](data)
|
| 1632 |
+
return data_val
|
| 1633 |
+
|
| 1634 |
+
iter_type = data_type[0] + data_type[-1]
|
| 1635 |
+
if iter_type in self.deserialize_type:
|
| 1636 |
+
return self.deserialize_type[iter_type](data, data_type[1:-1])
|
| 1637 |
+
|
| 1638 |
+
obj_type = self.dependencies[data_type]
|
| 1639 |
+
if issubclass(obj_type, Enum):
|
| 1640 |
+
if isinstance(data, ET.Element):
|
| 1641 |
+
data = data.text
|
| 1642 |
+
return self.deserialize_enum(data, obj_type)
|
| 1643 |
+
|
| 1644 |
+
except (ValueError, TypeError, AttributeError) as err:
|
| 1645 |
+
msg = "Unable to deserialize response data."
|
| 1646 |
+
msg += " Data: {}, {}".format(data, data_type)
|
| 1647 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1648 |
+
else:
|
| 1649 |
+
return self._deserialize(obj_type, data)
|
| 1650 |
+
|
| 1651 |
+
def deserialize_iter(self, attr, iter_type):
|
| 1652 |
+
"""Deserialize an iterable.
|
| 1653 |
+
|
| 1654 |
+
:param list attr: Iterable to be deserialized.
|
| 1655 |
+
:param str iter_type: The type of object in the iterable.
|
| 1656 |
+
:rtype: list
|
| 1657 |
+
"""
|
| 1658 |
+
if attr is None:
|
| 1659 |
+
return None
|
| 1660 |
+
if isinstance(attr, ET.Element): # If I receive an element here, get the children
|
| 1661 |
+
attr = list(attr)
|
| 1662 |
+
if not isinstance(attr, (list, set)):
|
| 1663 |
+
raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr)))
|
| 1664 |
+
return [self.deserialize_data(a, iter_type) for a in attr]
|
| 1665 |
+
|
| 1666 |
+
def deserialize_dict(self, attr, dict_type):
|
| 1667 |
+
"""Deserialize a dictionary.
|
| 1668 |
+
|
| 1669 |
+
:param dict/list attr: Dictionary to be deserialized. Also accepts
|
| 1670 |
+
a list of key, value pairs.
|
| 1671 |
+
:param str dict_type: The object type of the items in the dictionary.
|
| 1672 |
+
:rtype: dict
|
| 1673 |
+
"""
|
| 1674 |
+
if isinstance(attr, list):
|
| 1675 |
+
return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr}
|
| 1676 |
+
|
| 1677 |
+
if isinstance(attr, ET.Element):
|
| 1678 |
+
# Transform <Key>value</Key> into {"Key": "value"}
|
| 1679 |
+
attr = {el.tag: el.text for el in attr}
|
| 1680 |
+
return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()}
|
| 1681 |
+
|
| 1682 |
+
def deserialize_object(self, attr, **kwargs):
|
| 1683 |
+
"""Deserialize a generic object.
|
| 1684 |
+
This will be handled as a dictionary.
|
| 1685 |
+
|
| 1686 |
+
:param dict attr: Dictionary to be deserialized.
|
| 1687 |
+
:rtype: dict
|
| 1688 |
+
:raises: TypeError if non-builtin datatype encountered.
|
| 1689 |
+
"""
|
| 1690 |
+
if attr is None:
|
| 1691 |
+
return None
|
| 1692 |
+
if isinstance(attr, ET.Element):
|
| 1693 |
+
# Do no recurse on XML, just return the tree as-is
|
| 1694 |
+
return attr
|
| 1695 |
+
if isinstance(attr, basestring):
|
| 1696 |
+
return self.deserialize_basic(attr, "str")
|
| 1697 |
+
obj_type = type(attr)
|
| 1698 |
+
if obj_type in self.basic_types:
|
| 1699 |
+
return self.deserialize_basic(attr, self.basic_types[obj_type])
|
| 1700 |
+
if obj_type is _long_type:
|
| 1701 |
+
return self.deserialize_long(attr)
|
| 1702 |
+
|
| 1703 |
+
if obj_type == dict:
|
| 1704 |
+
deserialized = {}
|
| 1705 |
+
for key, value in attr.items():
|
| 1706 |
+
try:
|
| 1707 |
+
deserialized[key] = self.deserialize_object(value, **kwargs)
|
| 1708 |
+
except ValueError:
|
| 1709 |
+
deserialized[key] = None
|
| 1710 |
+
return deserialized
|
| 1711 |
+
|
| 1712 |
+
if obj_type == list:
|
| 1713 |
+
deserialized = []
|
| 1714 |
+
for obj in attr:
|
| 1715 |
+
try:
|
| 1716 |
+
deserialized.append(self.deserialize_object(obj, **kwargs))
|
| 1717 |
+
except ValueError:
|
| 1718 |
+
pass
|
| 1719 |
+
return deserialized
|
| 1720 |
+
|
| 1721 |
+
else:
|
| 1722 |
+
error = "Cannot deserialize generic object with type: "
|
| 1723 |
+
raise TypeError(error + str(obj_type))
|
| 1724 |
+
|
| 1725 |
+
def deserialize_basic(self, attr, data_type):
|
| 1726 |
+
"""Deserialize basic builtin data type from string.
|
| 1727 |
+
Will attempt to convert to str, int, float and bool.
|
| 1728 |
+
This function will also accept '1', '0', 'true' and 'false' as
|
| 1729 |
+
valid bool values.
|
| 1730 |
+
|
| 1731 |
+
:param str attr: response string to be deserialized.
|
| 1732 |
+
:param str data_type: deserialization data type.
|
| 1733 |
+
:rtype: str, int, float or bool
|
| 1734 |
+
:raises: TypeError if string format is not valid.
|
| 1735 |
+
"""
|
| 1736 |
+
# If we're here, data is supposed to be a basic type.
|
| 1737 |
+
# If it's still an XML node, take the text
|
| 1738 |
+
if isinstance(attr, ET.Element):
|
| 1739 |
+
attr = attr.text
|
| 1740 |
+
if not attr:
|
| 1741 |
+
if data_type == "str":
|
| 1742 |
+
# None or '', node <a/> is empty string.
|
| 1743 |
+
return ""
|
| 1744 |
+
else:
|
| 1745 |
+
# None or '', node <a/> with a strong type is None.
|
| 1746 |
+
# Don't try to model "empty bool" or "empty int"
|
| 1747 |
+
return None
|
| 1748 |
+
|
| 1749 |
+
if data_type == "bool":
|
| 1750 |
+
if attr in [True, False, 1, 0]:
|
| 1751 |
+
return bool(attr)
|
| 1752 |
+
elif isinstance(attr, basestring):
|
| 1753 |
+
if attr.lower() in ["true", "1"]:
|
| 1754 |
+
return True
|
| 1755 |
+
elif attr.lower() in ["false", "0"]:
|
| 1756 |
+
return False
|
| 1757 |
+
raise TypeError("Invalid boolean value: {}".format(attr))
|
| 1758 |
+
|
| 1759 |
+
if data_type == "str":
|
| 1760 |
+
return self.deserialize_unicode(attr)
|
| 1761 |
+
return eval(data_type)(attr) # nosec
|
| 1762 |
+
|
| 1763 |
+
@staticmethod
|
| 1764 |
+
def deserialize_unicode(data):
|
| 1765 |
+
"""Preserve unicode objects in Python 2, otherwise return data
|
| 1766 |
+
as a string.
|
| 1767 |
+
|
| 1768 |
+
:param str data: response string to be deserialized.
|
| 1769 |
+
:rtype: str or unicode
|
| 1770 |
+
"""
|
| 1771 |
+
# We might be here because we have an enum modeled as string,
|
| 1772 |
+
# and we try to deserialize a partial dict with enum inside
|
| 1773 |
+
if isinstance(data, Enum):
|
| 1774 |
+
return data
|
| 1775 |
+
|
| 1776 |
+
# Consider this is real string
|
| 1777 |
+
try:
|
| 1778 |
+
if isinstance(data, unicode): # type: ignore
|
| 1779 |
+
return data
|
| 1780 |
+
except NameError:
|
| 1781 |
+
return str(data)
|
| 1782 |
+
else:
|
| 1783 |
+
return str(data)
|
| 1784 |
+
|
| 1785 |
+
@staticmethod
|
| 1786 |
+
def deserialize_enum(data, enum_obj):
|
| 1787 |
+
"""Deserialize string into enum object.
|
| 1788 |
+
|
| 1789 |
+
If the string is not a valid enum value it will be returned as-is
|
| 1790 |
+
and a warning will be logged.
|
| 1791 |
+
|
| 1792 |
+
:param str data: Response string to be deserialized. If this value is
|
| 1793 |
+
None or invalid it will be returned as-is.
|
| 1794 |
+
:param Enum enum_obj: Enum object to deserialize to.
|
| 1795 |
+
:rtype: Enum
|
| 1796 |
+
"""
|
| 1797 |
+
if isinstance(data, enum_obj) or data is None:
|
| 1798 |
+
return data
|
| 1799 |
+
if isinstance(data, Enum):
|
| 1800 |
+
data = data.value
|
| 1801 |
+
if isinstance(data, int):
|
| 1802 |
+
# Workaround. We might consider remove it in the future.
|
| 1803 |
+
# https://github.com/Azure/azure-rest-api-specs/issues/141
|
| 1804 |
+
try:
|
| 1805 |
+
return list(enum_obj.__members__.values())[data]
|
| 1806 |
+
except IndexError:
|
| 1807 |
+
error = "{!r} is not a valid index for enum {!r}"
|
| 1808 |
+
raise DeserializationError(error.format(data, enum_obj))
|
| 1809 |
+
try:
|
| 1810 |
+
return enum_obj(str(data))
|
| 1811 |
+
except ValueError:
|
| 1812 |
+
for enum_value in enum_obj:
|
| 1813 |
+
if enum_value.value.lower() == str(data).lower():
|
| 1814 |
+
return enum_value
|
| 1815 |
+
# We don't fail anymore for unknown value, we deserialize as a string
|
| 1816 |
+
_LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj)
|
| 1817 |
+
return Deserializer.deserialize_unicode(data)
|
| 1818 |
+
|
| 1819 |
+
@staticmethod
|
| 1820 |
+
def deserialize_bytearray(attr):
|
| 1821 |
+
"""Deserialize string into bytearray.
|
| 1822 |
+
|
| 1823 |
+
:param str attr: response string to be deserialized.
|
| 1824 |
+
:rtype: bytearray
|
| 1825 |
+
:raises: TypeError if string format invalid.
|
| 1826 |
+
"""
|
| 1827 |
+
if isinstance(attr, ET.Element):
|
| 1828 |
+
attr = attr.text
|
| 1829 |
+
return bytearray(b64decode(attr)) # type: ignore
|
| 1830 |
+
|
| 1831 |
+
@staticmethod
|
| 1832 |
+
def deserialize_base64(attr):
|
| 1833 |
+
"""Deserialize base64 encoded string into string.
|
| 1834 |
+
|
| 1835 |
+
:param str attr: response string to be deserialized.
|
| 1836 |
+
:rtype: bytearray
|
| 1837 |
+
:raises: TypeError if string format invalid.
|
| 1838 |
+
"""
|
| 1839 |
+
if isinstance(attr, ET.Element):
|
| 1840 |
+
attr = attr.text
|
| 1841 |
+
padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore
|
| 1842 |
+
attr = attr + padding # type: ignore
|
| 1843 |
+
encoded = attr.replace("-", "+").replace("_", "/")
|
| 1844 |
+
return b64decode(encoded)
|
| 1845 |
+
|
| 1846 |
+
@staticmethod
|
| 1847 |
+
def deserialize_decimal(attr):
|
| 1848 |
+
"""Deserialize string into Decimal object.
|
| 1849 |
+
|
| 1850 |
+
:param str attr: response string to be deserialized.
|
| 1851 |
+
:rtype: Decimal
|
| 1852 |
+
:raises: DeserializationError if string format invalid.
|
| 1853 |
+
"""
|
| 1854 |
+
if isinstance(attr, ET.Element):
|
| 1855 |
+
attr = attr.text
|
| 1856 |
+
try:
|
| 1857 |
+
return decimal.Decimal(attr) # type: ignore
|
| 1858 |
+
except decimal.DecimalException as err:
|
| 1859 |
+
msg = "Invalid decimal {}".format(attr)
|
| 1860 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1861 |
+
|
| 1862 |
+
@staticmethod
|
| 1863 |
+
def deserialize_long(attr):
|
| 1864 |
+
"""Deserialize string into long (Py2) or int (Py3).
|
| 1865 |
+
|
| 1866 |
+
:param str attr: response string to be deserialized.
|
| 1867 |
+
:rtype: long or int
|
| 1868 |
+
:raises: ValueError if string format invalid.
|
| 1869 |
+
"""
|
| 1870 |
+
if isinstance(attr, ET.Element):
|
| 1871 |
+
attr = attr.text
|
| 1872 |
+
return _long_type(attr) # type: ignore
|
| 1873 |
+
|
| 1874 |
+
@staticmethod
|
| 1875 |
+
def deserialize_duration(attr):
|
| 1876 |
+
"""Deserialize ISO-8601 formatted string into TimeDelta object.
|
| 1877 |
+
|
| 1878 |
+
:param str attr: response string to be deserialized.
|
| 1879 |
+
:rtype: TimeDelta
|
| 1880 |
+
:raises: DeserializationError if string format invalid.
|
| 1881 |
+
"""
|
| 1882 |
+
if isinstance(attr, ET.Element):
|
| 1883 |
+
attr = attr.text
|
| 1884 |
+
try:
|
| 1885 |
+
duration = isodate.parse_duration(attr)
|
| 1886 |
+
except (ValueError, OverflowError, AttributeError) as err:
|
| 1887 |
+
msg = "Cannot deserialize duration object."
|
| 1888 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1889 |
+
else:
|
| 1890 |
+
return duration
|
| 1891 |
+
|
| 1892 |
+
@staticmethod
|
| 1893 |
+
def deserialize_date(attr):
|
| 1894 |
+
"""Deserialize ISO-8601 formatted string into Date object.
|
| 1895 |
+
|
| 1896 |
+
:param str attr: response string to be deserialized.
|
| 1897 |
+
:rtype: Date
|
| 1898 |
+
:raises: DeserializationError if string format invalid.
|
| 1899 |
+
"""
|
| 1900 |
+
if isinstance(attr, ET.Element):
|
| 1901 |
+
attr = attr.text
|
| 1902 |
+
if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore
|
| 1903 |
+
raise DeserializationError("Date must have only digits and -. Received: %s" % attr)
|
| 1904 |
+
# This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception.
|
| 1905 |
+
return isodate.parse_date(attr, defaultmonth=None, defaultday=None)
|
| 1906 |
+
|
| 1907 |
+
@staticmethod
|
| 1908 |
+
def deserialize_time(attr):
|
| 1909 |
+
"""Deserialize ISO-8601 formatted string into time object.
|
| 1910 |
+
|
| 1911 |
+
:param str attr: response string to be deserialized.
|
| 1912 |
+
:rtype: datetime.time
|
| 1913 |
+
:raises: DeserializationError if string format invalid.
|
| 1914 |
+
"""
|
| 1915 |
+
if isinstance(attr, ET.Element):
|
| 1916 |
+
attr = attr.text
|
| 1917 |
+
if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore
|
| 1918 |
+
raise DeserializationError("Date must have only digits and -. Received: %s" % attr)
|
| 1919 |
+
return isodate.parse_time(attr)
|
| 1920 |
+
|
| 1921 |
+
@staticmethod
|
| 1922 |
+
def deserialize_rfc(attr):
|
| 1923 |
+
"""Deserialize RFC-1123 formatted string into Datetime object.
|
| 1924 |
+
|
| 1925 |
+
:param str attr: response string to be deserialized.
|
| 1926 |
+
:rtype: Datetime
|
| 1927 |
+
:raises: DeserializationError if string format invalid.
|
| 1928 |
+
"""
|
| 1929 |
+
if isinstance(attr, ET.Element):
|
| 1930 |
+
attr = attr.text
|
| 1931 |
+
try:
|
| 1932 |
+
parsed_date = email.utils.parsedate_tz(attr) # type: ignore
|
| 1933 |
+
date_obj = datetime.datetime(
|
| 1934 |
+
*parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60))
|
| 1935 |
+
)
|
| 1936 |
+
if not date_obj.tzinfo:
|
| 1937 |
+
date_obj = date_obj.astimezone(tz=TZ_UTC)
|
| 1938 |
+
except ValueError as err:
|
| 1939 |
+
msg = "Cannot deserialize to rfc datetime object."
|
| 1940 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1941 |
+
else:
|
| 1942 |
+
return date_obj
|
| 1943 |
+
|
| 1944 |
+
@staticmethod
|
| 1945 |
+
def deserialize_iso(attr):
|
| 1946 |
+
"""Deserialize ISO-8601 formatted string into Datetime object.
|
| 1947 |
+
|
| 1948 |
+
:param str attr: response string to be deserialized.
|
| 1949 |
+
:rtype: Datetime
|
| 1950 |
+
:raises: DeserializationError if string format invalid.
|
| 1951 |
+
"""
|
| 1952 |
+
if isinstance(attr, ET.Element):
|
| 1953 |
+
attr = attr.text
|
| 1954 |
+
try:
|
| 1955 |
+
attr = attr.upper() # type: ignore
|
| 1956 |
+
match = Deserializer.valid_date.match(attr)
|
| 1957 |
+
if not match:
|
| 1958 |
+
raise ValueError("Invalid datetime string: " + attr)
|
| 1959 |
+
|
| 1960 |
+
check_decimal = attr.split(".")
|
| 1961 |
+
if len(check_decimal) > 1:
|
| 1962 |
+
decimal_str = ""
|
| 1963 |
+
for digit in check_decimal[1]:
|
| 1964 |
+
if digit.isdigit():
|
| 1965 |
+
decimal_str += digit
|
| 1966 |
+
else:
|
| 1967 |
+
break
|
| 1968 |
+
if len(decimal_str) > 6:
|
| 1969 |
+
attr = attr.replace(decimal_str, decimal_str[0:6])
|
| 1970 |
+
|
| 1971 |
+
date_obj = isodate.parse_datetime(attr)
|
| 1972 |
+
test_utc = date_obj.utctimetuple()
|
| 1973 |
+
if test_utc.tm_year > 9999 or test_utc.tm_year < 1:
|
| 1974 |
+
raise OverflowError("Hit max or min date")
|
| 1975 |
+
except (ValueError, OverflowError, AttributeError) as err:
|
| 1976 |
+
msg = "Cannot deserialize datetime object."
|
| 1977 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1978 |
+
else:
|
| 1979 |
+
return date_obj
|
| 1980 |
+
|
| 1981 |
+
@staticmethod
|
| 1982 |
+
def deserialize_unix(attr):
|
| 1983 |
+
"""Serialize Datetime object into IntTime format.
|
| 1984 |
+
This is represented as seconds.
|
| 1985 |
+
|
| 1986 |
+
:param int attr: Object to be serialized.
|
| 1987 |
+
:rtype: Datetime
|
| 1988 |
+
:raises: DeserializationError if format invalid
|
| 1989 |
+
"""
|
| 1990 |
+
if isinstance(attr, ET.Element):
|
| 1991 |
+
attr = int(attr.text) # type: ignore
|
| 1992 |
+
try:
|
| 1993 |
+
date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC)
|
| 1994 |
+
except ValueError as err:
|
| 1995 |
+
msg = "Cannot deserialize to unix datetime object."
|
| 1996 |
+
raise_with_traceback(DeserializationError, msg, err)
|
| 1997 |
+
else:
|
| 1998 |
+
return date_obj
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/_version.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
|
| 8 |
+
VERSION = "23.0.1"
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/changes/models.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
# --------------------------------------------------------------------------
|
| 7 |
+
from .v2022_05_01.models import *
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/__init__.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for license information.
|
| 5 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 6 |
+
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
|
| 7 |
+
# --------------------------------------------------------------------------
|
| 8 |
+
|
| 9 |
+
from ._deployment_scripts_client import DeploymentScriptsClient
|
| 10 |
+
__all__ = ['DeploymentScriptsClient']
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from ._patch import patch_sdk # type: ignore
|
| 14 |
+
patch_sdk()
|
| 15 |
+
except ImportError:
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
from ._version import VERSION
|
| 19 |
+
|
| 20 |
+
__version__ = VERSION
|
pgsql/pgAdmin 4/python/Lib/site-packages/azure/mgmt/resource/deploymentscripts/_configuration.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# --------------------------------------------------------------------------
|
| 3 |
+
# Copyright (c) Microsoft Corporation. All rights reserved.
|
| 4 |
+
# Licensed under the MIT License. See License.txt in the project root for
|
| 5 |
+
# license information.
|
| 6 |
+
#
|
| 7 |
+
# Code generated by Microsoft (R) AutoRest Code Generator.
|
| 8 |
+
# Changes may cause incorrect behavior and will be lost if the code is
|
| 9 |
+
# regenerated.
|
| 10 |
+
# --------------------------------------------------------------------------
|
| 11 |
+
from typing import Any, TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
from azure.core.configuration import Configuration
|
| 14 |
+
from azure.core.pipeline import policies
|
| 15 |
+
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
|
| 16 |
+
|
| 17 |
+
from ._version import VERSION
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
# pylint: disable=unused-import,ungrouped-imports
|
| 21 |
+
from azure.core.credentials import TokenCredential
|
| 22 |
+
|
| 23 |
+
class DeploymentScriptsClientConfiguration(Configuration):
|
| 24 |
+
"""Configuration for DeploymentScriptsClient.
|
| 25 |
+
|
| 26 |
+
Note that all parameters used to create this instance are saved as instance
|
| 27 |
+
attributes.
|
| 28 |
+
|
| 29 |
+
:param credential: Credential needed for the client to connect to Azure. Required.
|
| 30 |
+
:type credential: ~azure.core.credentials.TokenCredential
|
| 31 |
+
:param subscription_id: Subscription Id which forms part of the URI for every service call. Required.
|
| 32 |
+
:type subscription_id: str
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
credential: "TokenCredential",
|
| 38 |
+
subscription_id: str,
|
| 39 |
+
**kwargs: Any
|
| 40 |
+
):
|
| 41 |
+
if credential is None:
|
| 42 |
+
raise ValueError("Parameter 'credential' must not be None.")
|
| 43 |
+
if subscription_id is None:
|
| 44 |
+
raise ValueError("Parameter 'subscription_id' must not be None.")
|
| 45 |
+
super(DeploymentScriptsClientConfiguration, self).__init__(**kwargs)
|
| 46 |
+
|
| 47 |
+
self.credential = credential
|
| 48 |
+
self.subscription_id = subscription_id
|
| 49 |
+
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
|
| 50 |
+
kwargs.setdefault('sdk_moniker', 'azure-mgmt-resource/{}'.format(VERSION))
|
| 51 |
+
self._configure(**kwargs)
|
| 52 |
+
|
| 53 |
+
def _configure(
|
| 54 |
+
self,
|
| 55 |
+
**kwargs: Any
|
| 56 |
+
):
|
| 57 |
+
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
|
| 58 |
+
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
|
| 59 |
+
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
|
| 60 |
+
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
|
| 61 |
+
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
|
| 62 |
+
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
|
| 63 |
+
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
|
| 64 |
+
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
|
| 65 |
+
self.authentication_policy = kwargs.get('authentication_policy')
|
| 66 |
+
if self.credential and not self.authentication_policy:
|
| 67 |
+
self.authentication_policy = ARMChallengeAuthenticationPolicy(self.credential, *self.credential_scopes, **kwargs)
|