INSTRUCTION
stringlengths 1
8.43k
| RESPONSE
stringlengths 75
104k
|
|---|---|
Instance depends on the API version:
|
def replications(self):
"""Instance depends on the API version:
* 2017-10-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2017_10_01.operations.ReplicationsOperations>`
* 2018-02-01-preview: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.ReplicationsOperations>`
* 2018-09-01: :class:`ReplicationsOperations<azure.mgmt.containerregistry.v2018_09_01.operations.ReplicationsOperations>`
"""
api_version = self._get_api_version('replications')
if api_version == '2017-10-01':
from .v2017_10_01.operations import ReplicationsOperations as OperationClass
elif api_version == '2018-02-01-preview':
from .v2018_02_01_preview.operations import ReplicationsOperations as OperationClass
elif api_version == '2018-09-01':
from .v2018_09_01.operations import ReplicationsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def runs(self):
"""Instance depends on the API version:
* 2018-09-01: :class:`RunsOperations<azure.mgmt.containerregistry.v2018_09_01.operations.RunsOperations>`
"""
api_version = self._get_api_version('runs')
if api_version == '2018-09-01':
from .v2018_09_01.operations import RunsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def tasks(self):
"""Instance depends on the API version:
* 2018-09-01: :class:`TasksOperations<azure.mgmt.containerregistry.v2018_09_01.operations.TasksOperations>`
"""
api_version = self._get_api_version('tasks')
if api_version == '2018-09-01':
from .v2018_09_01.operations import TasksOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def webhooks(self):
"""Instance depends on the API version:
* 2017-10-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2017_10_01.operations.WebhooksOperations>`
* 2018-02-01-preview: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_02_01_preview.operations.WebhooksOperations>`
* 2018-09-01: :class:`WebhooksOperations<azure.mgmt.containerregistry.v2018_09_01.operations.WebhooksOperations>`
"""
api_version = self._get_api_version('webhooks')
if api_version == '2017-10-01':
from .v2017_10_01.operations import WebhooksOperations as OperationClass
elif api_version == '2018-02-01-preview':
from .v2018_02_01_preview.operations import WebhooksOperations as OperationClass
elif api_version == '2018-09-01':
from .v2018_09_01.operations import WebhooksOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Create message from response.
|
def _create_message(response, service_instance):
''' Create message from response.
response:
response from Service Bus cloud server.
service_instance:
the Service Bus client.
'''
respbody = response.body
custom_properties = {}
broker_properties = None
message_type = None
message_location = None
# gets all information from respheaders.
for name, value in response.headers:
if name.lower() == 'brokerproperties':
broker_properties = json.loads(value)
elif name.lower() == 'content-type':
message_type = value
elif name.lower() == 'location':
message_location = value
# Exclude common HTTP headers to avoid noise. List
# is not exhaustive. At worst, custom properties will contains
# an unexpected content generated by the webserver and not the customer.
elif name.lower() not in ['transfer-encoding',
'server',
'date',
'strict-transport-security']:
# Follow the spec:
# https://docs.microsoft.com/rest/api/servicebus/message-headers-and-properties
if '"' in value:
value = value[1:-1].replace('\\"', '"')
try:
custom_properties[name] = datetime.strptime(
value, '%a, %d %b %Y %H:%M:%S GMT')
except ValueError:
custom_properties[name] = value
elif value.lower() == 'true':
custom_properties[name] = True
elif value.lower() == 'false':
custom_properties[name] = False
else: # in theory, only int or float
try:
# int('3.1') doesn't work so need to get float('3.14') first
float_value = float(value)
if str(int(float_value)) == value:
custom_properties[name] = int(value)
else:
custom_properties[name] = float_value
except ValueError:
# If we are here, this header does not respect the spec.
# Could be an unexpected HTTP header or an invalid
# header value. In both case we ignore without failing.
pass
if message_type is None:
message = Message(
respbody, service_instance, message_location, custom_properties,
'application/atom+xml;type=entry;charset=utf-8', broker_properties)
else:
message = Message(respbody, service_instance, message_location,
custom_properties, message_type, broker_properties)
return message
|
Converts entry element to rule object.
|
def _convert_etree_element_to_rule(entry_element):
''' Converts entry element to rule object.
The format of xml for rule:
<entry xmlns='http://www.w3.org/2005/Atom'>
<content type='application/xml'>
<RuleDescription
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<Filter i:type="SqlFilterExpression">
<SqlExpression>MyProperty='XYZ'</SqlExpression>
</Filter>
<Action i:type="SqlFilterAction">
<SqlExpression>set MyProperty2 = 'ABC'</SqlExpression>
</Action>
</RuleDescription>
</content>
</entry>
'''
rule = Rule()
rule_element = entry_element.find('./atom:content/sb:RuleDescription', _etree_sb_feed_namespaces)
if rule_element is not None:
filter_element = rule_element.find('./sb:Filter', _etree_sb_feed_namespaces)
if filter_element is not None:
rule.filter_type = filter_element.attrib.get(
_make_etree_ns_attr_name(_etree_sb_feed_namespaces['i'], 'type'), None)
sql_exp_element = filter_element.find('./sb:SqlExpression', _etree_sb_feed_namespaces)
if sql_exp_element is not None:
rule.filter_expression = sql_exp_element.text
action_element = rule_element.find('./sb:Action', _etree_sb_feed_namespaces)
if action_element is not None:
rule.action_type = action_element.attrib.get(
_make_etree_ns_attr_name(_etree_sb_feed_namespaces['i'], 'type'), None)
sql_exp_element = action_element.find('./sb:SqlExpression', _etree_sb_feed_namespaces)
if sql_exp_element is not None:
rule.action_expression = sql_exp_element.text
# extract id, updated and name value from feed entry and set them of rule.
for name, value in _ETreeXmlToObject.get_entry_properties_from_element(
entry_element, True, '/rules').items():
setattr(rule, name, value)
return rule
|
Converts entry element to queue object.
|
def _convert_etree_element_to_queue(entry_element):
''' Converts entry element to queue object.
The format of xml response for queue:
<QueueDescription
xmlns=\"http://schemas.microsoft.com/netservices/2010/10/servicebus/connect\">
<MaxSizeInBytes>10000</MaxSizeInBytes>
<DefaultMessageTimeToLive>PT5M</DefaultMessageTimeToLive>
<LockDuration>PT2M</LockDuration>
<RequiresGroupedReceives>False</RequiresGroupedReceives>
<SupportsDuplicateDetection>False</SupportsDuplicateDetection>
...
</QueueDescription>
'''
queue = Queue()
# get node for each attribute in Queue class, if nothing found then the
# response is not valid xml for Queue.
invalid_queue = True
queue_element = entry_element.find('./atom:content/sb:QueueDescription', _etree_sb_feed_namespaces)
if queue_element is not None:
mappings = [
('LockDuration', 'lock_duration', None),
('MaxSizeInMegabytes', 'max_size_in_megabytes', int),
('RequiresDuplicateDetection', 'requires_duplicate_detection', _parse_bool),
('RequiresSession', 'requires_session', _parse_bool),
('DefaultMessageTimeToLive', 'default_message_time_to_live', None),
('DeadLetteringOnMessageExpiration', 'dead_lettering_on_message_expiration', _parse_bool),
('DuplicateDetectionHistoryTimeWindow', 'duplicate_detection_history_time_window', None),
('EnableBatchedOperations', 'enable_batched_operations', _parse_bool),
('MaxDeliveryCount', 'max_delivery_count', int),
('MessageCount', 'message_count', int),
('SizeInBytes', 'size_in_bytes', int),
]
for mapping in mappings:
if _read_etree_element(queue_element, mapping[0], queue, mapping[1], mapping[2]):
invalid_queue = False
if invalid_queue:
raise AzureServiceBusResourceNotFound(_ERROR_QUEUE_NOT_FOUND)
# extract id, updated and name value from feed entry and set them of queue.
for name, value in _ETreeXmlToObject.get_entry_properties_from_element(
entry_element, True).items():
setattr(queue, name, value)
return queue
|
Converts entry element to topic
|
def _convert_etree_element_to_topic(entry_element):
'''Converts entry element to topic
The xml format for topic:
<entry xmlns='http://www.w3.org/2005/Atom'>
<content type='application/xml'>
<TopicDescription
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<DefaultMessageTimeToLive>P10675199DT2H48M5.4775807S</DefaultMessageTimeToLive>
<MaxSizeInMegabytes>1024</MaxSizeInMegabytes>
<RequiresDuplicateDetection>false</RequiresDuplicateDetection>
<DuplicateDetectionHistoryTimeWindow>P7D</DuplicateDetectionHistoryTimeWindow>
<DeadLetteringOnFilterEvaluationExceptions>true</DeadLetteringOnFilterEvaluationExceptions>
</TopicDescription>
</content>
</entry>
'''
topic = Topic()
invalid_topic = True
topic_element = entry_element.find('./atom:content/sb:TopicDescription', _etree_sb_feed_namespaces)
if topic_element is not None:
mappings = [
('DefaultMessageTimeToLive', 'default_message_time_to_live', None),
('MaxSizeInMegabytes', 'max_size_in_megabytes', int),
('RequiresDuplicateDetection', 'requires_duplicate_detection', _parse_bool),
('DuplicateDetectionHistoryTimeWindow', 'duplicate_detection_history_time_window', None),
('EnableBatchedOperations', 'enable_batched_operations', _parse_bool),
('SizeInBytes', 'size_in_bytes', int),
]
for mapping in mappings:
if _read_etree_element(topic_element, mapping[0], topic, mapping[1], mapping[2]):
invalid_topic = False
if invalid_topic:
raise AzureServiceBusResourceNotFound(_ERROR_TOPIC_NOT_FOUND)
# extract id, updated and name value from feed entry and set them of topic.
for name, value in _ETreeXmlToObject.get_entry_properties_from_element(
entry_element, True).items():
setattr(topic, name, value)
return topic
|
Converts entry element to subscription
|
def _convert_etree_element_to_subscription(entry_element):
'''Converts entry element to subscription
The xml format for subscription:
<entry xmlns='http://www.w3.org/2005/Atom'>
<content type='application/xml'>
<SubscriptionDescription
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect">
<LockDuration>PT5M</LockDuration>
<RequiresSession>false</RequiresSession>
<DefaultMessageTimeToLive>P10675199DT2H48M5.4775807S</DefaultMessageTimeToLive>
<DeadLetteringOnMessageExpiration>false</DeadLetteringOnMessageExpiration>
<DeadLetteringOnFilterEvaluationExceptions>true</DeadLetteringOnFilterEvaluationExceptions>
</SubscriptionDescription>
</content>
</entry>
'''
subscription = Subscription()
subscription_element = entry_element.find('./atom:content/sb:SubscriptionDescription', _etree_sb_feed_namespaces)
if subscription_element is not None:
mappings = [
('LockDuration', 'lock_duration', None),
('RequiresSession', 'requires_session', _parse_bool),
('DefaultMessageTimeToLive', 'default_message_time_to_live', None),
('DeadLetteringOnFilterEvaluationExceptions', 'dead_lettering_on_filter_evaluation_exceptions', _parse_bool), # pylint: disable=line-too-long
('DeadLetteringOnMessageExpiration', 'dead_lettering_on_message_expiration', _parse_bool),
('EnableBatchedOperations', 'enable_batched_operations', _parse_bool),
('MaxDeliveryCount', 'max_delivery_count', int),
('MessageCount', 'message_count', int),
]
for mapping in mappings:
_read_etree_element(subscription_element, mapping[0], subscription, mapping[1], mapping[2])
for name, value in _ETreeXmlToObject.get_entry_properties_from_element(
entry_element, True, '/subscriptions').items():
setattr(subscription, name, value)
return subscription
|
Creates a new certificate inside the specified account.
|
def create(
self, resource_group_name, account_name, certificate_name, parameters, if_match=None, if_none_match=None, custom_headers=None, raw=False, **operation_config):
"""Creates a new certificate inside the specified account.
:param resource_group_name: The name of the resource group that
contains the Batch account.
:type resource_group_name: str
:param account_name: The name of the Batch account.
:type account_name: str
:param certificate_name: The identifier for the certificate. This must
be made up of algorithm and thumbprint separated by a dash, and must
match the certificate data in the request. For example SHA1-a3d1c5.
:type certificate_name: str
:param parameters: Additional parameters for certificate creation.
:type parameters:
~azure.mgmt.batch.models.CertificateCreateOrUpdateParameters
:param if_match: The entity state (ETag) version of the certificate to
update. A value of "*" can be used to apply the operation only if the
certificate already exists. If omitted, this operation will always be
applied.
:type if_match: str
:param if_none_match: Set to '*' to allow a new certificate to be
created, but to prevent updating an existing certificate. Other values
will be ignored.
:type if_none_match: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:return: An instance of AzureOperationPoller that returns Certificate
or ClientRawResponse if raw=true
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.batch.models.Certificate]
or ~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._create_initial(
resource_group_name=resource_group_name,
account_name=account_name,
certificate_name=certificate_name,
parameters=parameters,
if_match=if_match,
if_none_match=if_none_match,
custom_headers=custom_headers,
raw=True,
**operation_config
)
if raw:
return raw_result
# Construct and send request
def long_running_send():
return raw_result.response
def get_long_running_status(status_link, headers=None):
request = self._client.get(status_link)
if headers:
request.headers.update(headers)
header_parameters = {}
header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id']
return self._client.send(
request, header_parameters, stream=False, **operation_config)
def get_long_running_output(response):
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
header_dict = {
'ETag': 'str',
}
deserialized = self._deserialize('Certificate', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
client_raw_response.add_headers(header_dict)
return client_raw_response
return deserialized
long_running_operation_timeout = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
return AzureOperationPoller(
long_running_send, get_long_running_output,
get_long_running_status, long_running_operation_timeout)
|
Deletes the specified certificate.
|
def delete(
self, resource_group_name, account_name, certificate_name, custom_headers=None, raw=False, **operation_config):
"""Deletes the specified certificate.
:param resource_group_name: The name of the resource group that
contains the Batch account.
:type resource_group_name: str
:param account_name: The name of the Batch account.
:type account_name: str
:param certificate_name: The identifier for the certificate. This must
be made up of algorithm and thumbprint separated by a dash, and must
match the certificate data in the request. For example SHA1-a3d1c5.
:type certificate_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:return: An instance of AzureOperationPoller that returns None or
ClientRawResponse if raw=true
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._delete_initial(
resource_group_name=resource_group_name,
account_name=account_name,
certificate_name=certificate_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
if raw:
return raw_result
# Construct and send request
def long_running_send():
return raw_result.response
def get_long_running_status(status_link, headers=None):
request = self._client.get(status_link)
if headers:
request.headers.update(headers)
header_parameters = {}
header_parameters['x-ms-client-request-id'] = raw_result.response.request.headers['x-ms-client-request-id']
return self._client.send(
request, header_parameters, stream=False, **operation_config)
def get_long_running_output(response):
if response.status_code not in [200, 202, 204]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
if raw:
client_raw_response = ClientRawResponse(None, response)
client_raw_response.add_headers({
'Location': 'str',
'Retry-After': 'int',
})
return client_raw_response
long_running_operation_timeout = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
return AzureOperationPoller(
long_running_send, get_long_running_output,
get_long_running_status, long_running_operation_timeout)
|
Main method
|
def update_pr_main():
"""Main method"""
parser = argparse.ArgumentParser(
description='Build package.',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--pr-number', '-p',
dest='pr_number', type=int, required=True,
help='PR number')
parser.add_argument('--repo', '-r',
dest='repo_id', default="Azure/azure-sdk-for-python",
help='Repo id. [default: %(default)s]')
parser.add_argument("-v", "--verbose",
dest="verbose", action="store_true",
help="Verbosity in INFO mode")
parser.add_argument("--debug",
dest="debug", action="store_true",
help="Verbosity in DEBUG mode")
args = parser.parse_args()
main_logger = logging.getLogger()
if args.verbose or args.debug:
logging.basicConfig()
main_logger.setLevel(logging.DEBUG if args.debug else logging.INFO)
update_pr(
os.environ.get("GH_TOKEN", None),
args.repo_id,
int(args.pr_number),
)
|
Instantiate a client from kwargs removing the subscription_id/ tenant_id argument if unsupported.
|
def _instantiate_client(client_class, **kwargs):
"""Instantiate a client from kwargs, removing the subscription_id/tenant_id argument if unsupported.
"""
args = get_arg_spec(client_class.__init__).args
for key in ['subscription_id', 'tenant_id']:
if key not in kwargs:
continue
if key not in args:
del kwargs[key]
elif sys.version_info < (3, 0) and isinstance(kwargs[key], unicode):
kwargs[key] = kwargs[key].encode('utf-8')
return client_class(**kwargs)
|
Return a tuple of the resource ( used to get the right access token ) and the base URL for the client. Either or both can be None to signify that the default value should be used.
|
def _client_resource(client_class, cloud):
"""Return a tuple of the resource (used to get the right access token), and the base URL for the client.
Either or both can be None to signify that the default value should be used.
"""
if client_class.__name__ == 'GraphRbacManagementClient':
return cloud.endpoints.active_directory_graph_resource_id, cloud.endpoints.active_directory_graph_resource_id
if client_class.__name__ == 'KeyVaultClient':
vault_host = cloud.suffixes.keyvault_dns[1:]
vault_url = 'https://{}'.format(vault_host)
return vault_url, None
return None, None
|
Return a SDK client initialized with current CLI credentials CLI default subscription and CLI default cloud.
|
def get_client_from_cli_profile(client_class, **kwargs):
"""Return a SDK client initialized with current CLI credentials, CLI default subscription and CLI default cloud.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters provided in kwargs will override CLI parameters and be passed directly to the client.
:Example:
.. code:: python
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.compute import ComputeManagementClient
client = get_client_from_cli_profile(ComputeManagementClient)
.. versionadded:: 1.1.6
:param client_class: A SDK client class
:return: An instantiated client
:raises: ImportError if azure-cli-core package is not available
"""
cloud = get_cli_active_cloud()
parameters = {}
if 'credentials' not in kwargs or 'subscription_id' not in kwargs:
resource, _ = _client_resource(client_class, cloud)
credentials, subscription_id, tenant_id = get_azure_cli_credentials(resource=resource,
with_tenant=True)
parameters.update({
'credentials': kwargs.get('credentials', credentials),
'subscription_id': kwargs.get('subscription_id', subscription_id)
})
args = get_arg_spec(client_class.__init__).args
if 'adla_job_dns_suffix' in args and 'adla_job_dns_suffix' not in kwargs: # Datalake
# Let it raise here with AttributeError at worst, this would mean this cloud does not define
# ADL endpoint and no manual suffix was given
parameters['adla_job_dns_suffix'] = cloud.suffixes.azure_datalake_analytics_catalog_and_job_endpoint
elif 'base_url' in args and 'base_url' not in kwargs:
_, base_url = _client_resource(client_class, cloud)
if base_url:
parameters['base_url'] = base_url
else:
parameters['base_url'] = cloud.endpoints.resource_manager
if 'tenant_id' in args and 'tenant_id' not in kwargs:
parameters['tenant_id'] = tenant_id
parameters.update(kwargs)
return _instantiate_client(client_class, **parameters)
|
Return a SDK client initialized with a JSON auth dict.
|
def get_client_from_json_dict(client_class, config_dict, **kwargs):
"""Return a SDK client initialized with a JSON auth dict.
The easiest way to obtain this content is to call the following CLI commands:
.. code:: bash
az ad sp create-for-rbac --sdk-auth
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
- tenant_id
Parameters provided in kwargs will override parameters and be passed directly to the client.
:Example:
.. code:: python
from azure.common.client_factory import get_client_from_auth_file
from azure.mgmt.compute import ComputeManagementClient
config_dict = {
"clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e",
"clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e",
"subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e",
"tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
client = get_client_from_json_dict(ComputeManagementClient, config_dict)
.. versionadded:: 1.1.7
:param client_class: A SDK client class
:param dict config_dict: A config dict.
:return: An instantiated client
"""
is_graphrbac = client_class.__name__ == 'GraphRbacManagementClient'
parameters = {
'subscription_id': config_dict.get('subscriptionId'),
'base_url': config_dict.get('resourceManagerEndpointUrl'),
'tenant_id': config_dict.get('tenantId') # GraphRbac
}
if is_graphrbac:
parameters['base_url'] = config_dict['activeDirectoryGraphResourceId']
if 'credentials' not in kwargs:
# Get the right resource for Credentials
if is_graphrbac:
resource = config_dict['activeDirectoryGraphResourceId']
else:
if "activeDirectoryResourceId" not in config_dict and 'resourceManagerEndpointUrl' not in config_dict:
raise ValueError("Need activeDirectoryResourceId or resourceManagerEndpointUrl key")
resource = config_dict.get('activeDirectoryResourceId', config_dict['resourceManagerEndpointUrl'])
authority_url = config_dict['activeDirectoryEndpointUrl']
is_adfs = bool(re.match('.+(/adfs|/adfs/)$', authority_url, re.I))
if is_adfs:
authority_url = authority_url.rstrip('/') # workaround: ADAL is known to reject auth urls with trailing /
else:
authority_url = authority_url + '/' + config_dict['tenantId']
context = adal.AuthenticationContext(
authority_url,
api_version=None,
validate_authority=not is_adfs
)
parameters['credentials'] = AdalAuthentication(
context.acquire_token_with_client_credentials,
resource,
config_dict['clientId'],
config_dict['clientSecret']
)
parameters.update(kwargs)
return _instantiate_client(client_class, **parameters)
|
Return a SDK client initialized with auth file.
|
def get_client_from_auth_file(client_class, auth_path=None, **kwargs):
"""Return a SDK client initialized with auth file.
The easiest way to obtain this file is to call the following CLI commands:
.. code:: bash
az ad sp create-for-rbac --sdk-auth
You can specific the file path directly, or fill the environment variable AZURE_AUTH_LOCATION.
File must be UTF-8.
This method will fill automatically the following client parameters:
- credentials
- subscription_id
- base_url
Parameters provided in kwargs will override parameters and be passed directly to the client.
:Example:
.. code:: python
from azure.common.client_factory import get_client_from_auth_file
from azure.mgmt.compute import ComputeManagementClient
client = get_client_from_auth_file(ComputeManagementClient)
Example of file:
.. code:: json
{
"clientId": "ad735158-65ca-11e7-ba4d-ecb1d756380e",
"clientSecret": "b70bb224-65ca-11e7-810c-ecb1d756380e",
"subscriptionId": "bfc42d3a-65ca-11e7-95cf-ecb1d756380e",
"tenantId": "c81da1d8-65ca-11e7-b1d1-ecb1d756380e",
"activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
"resourceManagerEndpointUrl": "https://management.azure.com/",
"activeDirectoryGraphResourceId": "https://graph.windows.net/",
"sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
"galleryEndpointUrl": "https://gallery.azure.com/",
"managementEndpointUrl": "https://management.core.windows.net/"
}
.. versionadded:: 1.1.7
:param client_class: A SDK client class
:param str auth_path: Path to the file.
:return: An instantiated client
:raises: KeyError if AZURE_AUTH_LOCATION is not an environment variable and no path is provided
:raises: FileNotFoundError if provided file path does not exists
:raises: json.JSONDecodeError if provided file is not JSON valid
:raises: UnicodeDecodeError if file is not UTF8 compliant
"""
auth_path = auth_path or os.environ['AZURE_AUTH_LOCATION']
with io.open(auth_path, 'r', encoding='utf-8-sig') as auth_fd:
config_dict = json.load(auth_fd)
return get_client_from_json_dict(client_class, config_dict, **kwargs)
|
Parse the HTTPResponse s body and fill all the data into a class of return_type.
|
def parse_response(response, return_type):
'''
Parse the HTTPResponse's body and fill all the data into a class of
return_type.
'''
root = ETree.fromstring(response.body)
xml_name = getattr(return_type, '_xml_name', return_type.__name__)
if root.tag == xml_name:
return _ETreeXmlToObject._parse_response_body_from_xml_node(root, return_type)
return None
|
resp_body is the XML we received resp_type is a string such as Containers return_type is the type we re constructing such as ContainerEnumResults item_type is the type object of the item to be created such as Container
|
def parse_enum_results_list(response, return_type, resp_type, item_type):
"""resp_body is the XML we received
resp_type is a string, such as Containers,
return_type is the type we're constructing, such as ContainerEnumResults
item_type is the type object of the item to be created, such as Container
This function then returns a ContainerEnumResults object with the
containers member populated with the results.
"""
# parsing something like:
# <EnumerationResults ... >
# <Queues>
# <Queue>
# <Something />
# <SomethingElse />
# </Queue>
# </Queues>
# </EnumerationResults>
return_obj = return_type()
root = ETree.fromstring(response.body)
items = []
for container_element in root.findall(resp_type):
for item_element in container_element.findall(resp_type[:-1]):
items.append(_ETreeXmlToObject.fill_instance_element(item_element, item_type))
for name, value in vars(return_obj).items():
# queues, Queues, this is the list its self which we populated
# above
if name == resp_type.lower():
# the list its self.
continue
value = _ETreeXmlToObject.fill_data_member(root, name, value)
if value is not None:
setattr(return_obj, name, value)
setattr(return_obj, resp_type.lower(), items)
return return_obj
|
get properties from element tree element
|
def get_entry_properties_from_element(element, include_id, id_prefix_to_skip=None, use_title_as_id=False):
''' get properties from element tree element '''
properties = {}
etag = element.attrib.get(_make_etree_ns_attr_name(_etree_entity_feed_namespaces['m'], 'etag'), None)
if etag is not None:
properties['etag'] = etag
updated = element.findtext('./atom:updated', '', _etree_entity_feed_namespaces)
if updated:
properties['updated'] = updated
author_name = element.findtext('./atom:author/atom:name', '', _etree_entity_feed_namespaces)
if author_name:
properties['author'] = author_name
if include_id:
if use_title_as_id:
title = element.findtext('./atom:title', '', _etree_entity_feed_namespaces)
if title:
properties['name'] = title
else:
element_id = element.findtext('./atom:id', '', _etree_entity_feed_namespaces)
if element_id:
properties['name'] = _get_readable_id(element_id, id_prefix_to_skip)
return properties
|
parse the xml and fill all the data into a class of return_type
|
def _parse_response_body_from_xml_node(node, return_type):
'''
parse the xml and fill all the data into a class of return_type
'''
return_obj = return_type()
_ETreeXmlToObject._fill_data_to_return_object(node, return_obj)
return return_obj
|
Converts a child of the current dom element to the specified type.
|
def _fill_instance_child(xmldoc, element_name, return_type):
'''Converts a child of the current dom element to the specified type.
'''
element = xmldoc.find(_get_serialization_name(element_name))
if element is None:
return None
return_obj = return_type()
_ETreeXmlToObject._fill_data_to_return_object(element, return_obj)
return return_obj
|
Checks whether a domain name in the cloudapp. azure. com zone is available for use.
|
def check_dns_name_availability(
self, location, domain_name_label, custom_headers=None, raw=False, **operation_config):
"""Checks whether a domain name in the cloudapp.azure.com zone is
available for use.
:param location: The location of the domain name.
:type location: str
:param domain_name_label: The domain name to be verified. It must
conform to the following regular expression:
^[a-z][a-z0-9-]{1,61}[a-z0-9]$.
:type domain_name_label: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: :class:`DnsNameAvailabilityResult
<azure.mgmt.network.v2018_08_01.models.DnsNameAvailabilityResult>` or
:class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>` if
raw=true
:rtype: :class:`DnsNameAvailabilityResult
<azure.mgmt.network.v2018_08_01.models.DnsNameAvailabilityResult>` or
:class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
api_version = self._get_api_version('check_dns_name_availability')
if api_version == '2018-12-01':
from .v2018_12_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-11-01':
from .v2018_11_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-10-01':
from .v2018_10_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-08-01':
from .v2018_08_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-07-01':
from .v2018_07_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-06-01':
from .v2018_06_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-04-01':
from .v2018_04_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-02-01':
from .v2018_02_01 import NetworkManagementClient as ClientClass
elif api_version == '2018-01-01':
from .v2018_01_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-11-01':
from .v2017_11_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-10-01':
from .v2017_10_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-09-01':
from .v2017_09_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-08-01':
from .v2017_08_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-06-01':
from .v2017_06_01 import NetworkManagementClient as ClientClass
elif api_version == '2017-03-01':
from .v2017_03_01 import NetworkManagementClient as ClientClass
elif api_version == '2016-12-01':
from .v2016_12_01 import NetworkManagementClient as ClientClass
elif api_version == '2016-09-01':
from .v2016_09_01 import NetworkManagementClient as ClientClass
elif api_version == '2015-06-15':
from .v2015_06_15 import NetworkManagementClient as ClientClass
localclient = ClientClass(self.config.credentials,
self.config.subscription_id,
self.config.base_url)
return localclient.check_dns_name_availability(location,
domain_name_label,
custom_headers,
raw,
**operation_config)
|
Instance depends on the API version:
|
def ddos_custom_policies(self):
"""Instance depends on the API version:
* 2018-11-01: :class:`DdosCustomPoliciesOperations<azure.mgmt.network.v2018_11_01.operations.DdosCustomPoliciesOperations>`
* 2018-12-01: :class:`DdosCustomPoliciesOperations<azure.mgmt.network.v2018_12_01.operations.DdosCustomPoliciesOperations>`
* 2019-02-01: :class:`DdosCustomPoliciesOperations<azure.mgmt.network.v2019_02_01.operations.DdosCustomPoliciesOperations>`
"""
api_version = self._get_api_version('ddos_custom_policies')
if api_version == '2018-11-01':
from .v2018_11_01.operations import DdosCustomPoliciesOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import DdosCustomPoliciesOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import DdosCustomPoliciesOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def express_route_connections(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`ExpressRouteConnectionsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRouteConnectionsOperations>`
* 2018-10-01: :class:`ExpressRouteConnectionsOperations<azure.mgmt.network.v2018_10_01.operations.ExpressRouteConnectionsOperations>`
* 2018-11-01: :class:`ExpressRouteConnectionsOperations<azure.mgmt.network.v2018_11_01.operations.ExpressRouteConnectionsOperations>`
* 2018-12-01: :class:`ExpressRouteConnectionsOperations<azure.mgmt.network.v2018_12_01.operations.ExpressRouteConnectionsOperations>`
* 2019-02-01: :class:`ExpressRouteConnectionsOperations<azure.mgmt.network.v2019_02_01.operations.ExpressRouteConnectionsOperations>`
"""
api_version = self._get_api_version('express_route_connections')
if api_version == '2018-08-01':
from .v2018_08_01.operations import ExpressRouteConnectionsOperations as OperationClass
elif api_version == '2018-10-01':
from .v2018_10_01.operations import ExpressRouteConnectionsOperations as OperationClass
elif api_version == '2018-11-01':
from .v2018_11_01.operations import ExpressRouteConnectionsOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import ExpressRouteConnectionsOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import ExpressRouteConnectionsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def express_route_cross_connection_peerings(self):
"""Instance depends on the API version:
* 2018-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-04-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_04_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-06-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_06_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-07-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_07_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-08-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_08_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-10-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_10_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-11-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_11_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2018-12-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2018_12_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
* 2019-02-01: :class:`ExpressRouteCrossConnectionPeeringsOperations<azure.mgmt.network.v2019_02_01.operations.ExpressRouteCrossConnectionPeeringsOperations>`
"""
api_version = self._get_api_version('express_route_cross_connection_peerings')
if api_version == '2018-02-01':
from .v2018_02_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-04-01':
from .v2018_04_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-06-01':
from .v2018_06_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-07-01':
from .v2018_07_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-08-01':
from .v2018_08_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-10-01':
from .v2018_10_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-11-01':
from .v2018_11_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import ExpressRouteCrossConnectionPeeringsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def hub_virtual_network_connections(self):
"""Instance depends on the API version:
* 2018-04-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_04_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-06-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_06_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-07-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_07_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-08-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_08_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-10-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_10_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-11-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_11_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2018-12-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2018_12_01.operations.HubVirtualNetworkConnectionsOperations>`
* 2019-02-01: :class:`HubVirtualNetworkConnectionsOperations<azure.mgmt.network.v2019_02_01.operations.HubVirtualNetworkConnectionsOperations>`
"""
api_version = self._get_api_version('hub_virtual_network_connections')
if api_version == '2018-04-01':
from .v2018_04_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-06-01':
from .v2018_06_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-07-01':
from .v2018_07_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-08-01':
from .v2018_08_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-10-01':
from .v2018_10_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-11-01':
from .v2018_11_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import HubVirtualNetworkConnectionsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def nat_gateways(self):
"""Instance depends on the API version:
* 2019-02-01: :class:`NatGatewaysOperations<azure.mgmt.network.v2019_02_01.operations.NatGatewaysOperations>`
"""
api_version = self._get_api_version('nat_gateways')
if api_version == '2019-02-01':
from .v2019_02_01.operations import NatGatewaysOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def network_watchers(self):
"""Instance depends on the API version:
* 2016-09-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2016_09_01.operations.NetworkWatchersOperations>`
* 2016-12-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2016_12_01.operations.NetworkWatchersOperations>`
* 2017-03-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_03_01.operations.NetworkWatchersOperations>`
* 2017-06-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_06_01.operations.NetworkWatchersOperations>`
* 2017-08-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_08_01.operations.NetworkWatchersOperations>`
* 2017-09-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_09_01.operations.NetworkWatchersOperations>`
* 2017-10-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_10_01.operations.NetworkWatchersOperations>`
* 2017-11-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2017_11_01.operations.NetworkWatchersOperations>`
* 2018-01-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_01_01.operations.NetworkWatchersOperations>`
* 2018-02-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_02_01.operations.NetworkWatchersOperations>`
* 2018-04-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_04_01.operations.NetworkWatchersOperations>`
* 2018-06-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_06_01.operations.NetworkWatchersOperations>`
* 2018-07-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_07_01.operations.NetworkWatchersOperations>`
* 2018-08-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_08_01.operations.NetworkWatchersOperations>`
* 2018-10-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_10_01.operations.NetworkWatchersOperations>`
* 2018-11-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_11_01.operations.NetworkWatchersOperations>`
* 2018-12-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2018_12_01.operations.NetworkWatchersOperations>`
* 2019-02-01: :class:`NetworkWatchersOperations<azure.mgmt.network.v2019_02_01.operations.NetworkWatchersOperations>`
"""
api_version = self._get_api_version('network_watchers')
if api_version == '2016-09-01':
from .v2016_09_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2016-12-01':
from .v2016_12_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-03-01':
from .v2017_03_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-06-01':
from .v2017_06_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-08-01':
from .v2017_08_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-09-01':
from .v2017_09_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-10-01':
from .v2017_10_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2017-11-01':
from .v2017_11_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-01-01':
from .v2018_01_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-02-01':
from .v2018_02_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-04-01':
from .v2018_04_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-06-01':
from .v2018_06_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-07-01':
from .v2018_07_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-08-01':
from .v2018_08_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-10-01':
from .v2018_10_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-11-01':
from .v2018_11_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import NetworkWatchersOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import NetworkWatchersOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def peer_express_route_circuit_connections(self):
"""Instance depends on the API version:
* 2018-12-01: :class:`PeerExpressRouteCircuitConnectionsOperations<azure.mgmt.network.v2018_12_01.operations.PeerExpressRouteCircuitConnectionsOperations>`
* 2019-02-01: :class:`PeerExpressRouteCircuitConnectionsOperations<azure.mgmt.network.v2019_02_01.operations.PeerExpressRouteCircuitConnectionsOperations>`
"""
api_version = self._get_api_version('peer_express_route_circuit_connections')
if api_version == '2018-12-01':
from .v2018_12_01.operations import PeerExpressRouteCircuitConnectionsOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import PeerExpressRouteCircuitConnectionsOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def service_endpoint_policies(self):
"""Instance depends on the API version:
* 2018-07-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2018_07_01.operations.ServiceEndpointPoliciesOperations>`
* 2018-08-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2018_08_01.operations.ServiceEndpointPoliciesOperations>`
* 2018-10-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2018_10_01.operations.ServiceEndpointPoliciesOperations>`
* 2018-11-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2018_11_01.operations.ServiceEndpointPoliciesOperations>`
* 2018-12-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2018_12_01.operations.ServiceEndpointPoliciesOperations>`
* 2019-02-01: :class:`ServiceEndpointPoliciesOperations<azure.mgmt.network.v2019_02_01.operations.ServiceEndpointPoliciesOperations>`
"""
api_version = self._get_api_version('service_endpoint_policies')
if api_version == '2018-07-01':
from .v2018_07_01.operations import ServiceEndpointPoliciesOperations as OperationClass
elif api_version == '2018-08-01':
from .v2018_08_01.operations import ServiceEndpointPoliciesOperations as OperationClass
elif api_version == '2018-10-01':
from .v2018_10_01.operations import ServiceEndpointPoliciesOperations as OperationClass
elif api_version == '2018-11-01':
from .v2018_11_01.operations import ServiceEndpointPoliciesOperations as OperationClass
elif api_version == '2018-12-01':
from .v2018_12_01.operations import ServiceEndpointPoliciesOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import ServiceEndpointPoliciesOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Instance depends on the API version:
|
def web_application_firewall_policies(self):
"""Instance depends on the API version:
* 2018-12-01: :class:`WebApplicationFirewallPoliciesOperations<azure.mgmt.network.v2018_12_01.operations.WebApplicationFirewallPoliciesOperations>`
* 2019-02-01: :class:`WebApplicationFirewallPoliciesOperations<azure.mgmt.network.v2019_02_01.operations.WebApplicationFirewallPoliciesOperations>`
"""
api_version = self._get_api_version('web_application_firewall_policies')
if api_version == '2018-12-01':
from .v2018_12_01.operations import WebApplicationFirewallPoliciesOperations as OperationClass
elif api_version == '2019-02-01':
from .v2019_02_01.operations import WebApplicationFirewallPoliciesOperations as OperationClass
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
|
Delete the Provisioning Service Certificate.
|
def delete(
self, resource_group_name, if_match, provisioning_service_name, certificate_name, certificatename=None, certificateraw_bytes=None, certificateis_verified=None, certificatepurpose=None, certificatecreated=None, certificatelast_updated=None, certificatehas_private_key=None, certificatenonce=None, custom_headers=None, raw=False, **operation_config):
"""Delete the Provisioning Service Certificate.
Deletes the specified certificate assosciated with the Provisioning
Service.
:param resource_group_name: Resource group identifier.
:type resource_group_name: str
:param if_match: ETag of the certificate
:type if_match: str
:param provisioning_service_name: The name of the provisioning
service.
:type provisioning_service_name: str
:param certificate_name: This is a mandatory field, and is the logical
name of the certificate that the provisioning service will access by.
:type certificate_name: str
:param certificatename: This is optional, and it is the Common Name of
the certificate.
:type certificatename: str
:param certificateraw_bytes: Raw data within the certificate.
:type certificateraw_bytes: bytearray
:param certificateis_verified: Indicates if certificate has been
verified by owner of the private key.
:type certificateis_verified: bool
:param certificatepurpose: A description that mentions the purpose of
the certificate. Possible values include: 'clientAuthentication',
'serverAuthentication'
:type certificatepurpose: str or
~azure.mgmt.iothubprovisioningservices.models.CertificatePurpose
:param certificatecreated: Time the certificate is created.
:type certificatecreated: datetime
:param certificatelast_updated: Time the certificate is last updated.
:type certificatelast_updated: datetime
:param certificatehas_private_key: Indicates if the certificate
contains a private key.
:type certificatehas_private_key: bool
:param certificatenonce: Random number generated to indicate Proof of
Possession.
:type certificatenonce: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorDetailsException<azure.mgmt.iothubprovisioningservices.models.ErrorDetailsException>`
"""
# Construct URL
url = self.delete.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'provisioningServiceName': self._serialize.url("provisioning_service_name", provisioning_service_name, 'str'),
'certificateName': self._serialize.url("certificate_name", certificate_name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if certificatename is not None:
query_parameters['certificate.name'] = self._serialize.query("certificatename", certificatename, 'str')
if certificateraw_bytes is not None:
query_parameters['certificate.rawBytes'] = self._serialize.query("certificateraw_bytes", certificateraw_bytes, 'bytearray')
if certificateis_verified is not None:
query_parameters['certificate.isVerified'] = self._serialize.query("certificateis_verified", certificateis_verified, 'bool')
if certificatepurpose is not None:
query_parameters['certificate.purpose'] = self._serialize.query("certificatepurpose", certificatepurpose, 'str')
if certificatecreated is not None:
query_parameters['certificate.created'] = self._serialize.query("certificatecreated", certificatecreated, 'iso-8601')
if certificatelast_updated is not None:
query_parameters['certificate.lastUpdated'] = self._serialize.query("certificatelast_updated", certificatelast_updated, 'iso-8601')
if certificatehas_private_key is not None:
query_parameters['certificate.hasPrivateKey'] = self._serialize.query("certificatehas_private_key", certificatehas_private_key, 'bool')
if certificatenonce is not None:
query_parameters['certificate.nonce'] = self._serialize.query("certificatenonce", certificatenonce, 'str')
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.delete(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if response.status_code not in [200, 204]:
raise models.ErrorDetailsException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
|
List all entities ( Management Groups Subscriptions etc. ) for the authenticated user.
|
def list(
self, skiptoken=None, skip=None, top=None, select=None, search=None, filter=None, view=None, group_name=None, cache_control="no-cache", custom_headers=None, raw=False, **operation_config):
"""List all entities (Management Groups, Subscriptions, etc.) for the
authenticated user.
:param skiptoken: Page continuation token is only used if a previous
operation returned a partial result. If a previous response contains a
nextLink element, the value of the nextLink element will include a
token parameter that specifies a starting point to use for subsequent
calls.
:type skiptoken: str
:param skip: Number of entities to skip over when retrieving results.
Passing this in will override $skipToken.
:type skip: int
:param top: Number of elements to return when retrieving results.
Passing this in will override $skipToken.
:type top: int
:param select: This parameter specifies the fields to include in the
response. Can include any combination of
Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, e.g.
'$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'.
When specified the $select parameter can override select in
$skipToken.
:type select: str
:param search: The $search parameter is used in conjunction with the
$filter parameter to return three different outputs depending on the
parameter passed in. With $search=AllowedParents the API will return
the entity info of all groups that the requested entity will be able
to reparent to as determined by the user's permissions. With
$search=AllowedChildren the API will return the entity info of all
entities that can be added as children of the requested entity. With
$search=ParentAndFirstLevelChildren the API will return the parent and
first level of children that the user has either direct access to or
indirect access via one of their descendants. Possible values include:
'AllowedParents', 'AllowedChildren', 'ParentAndFirstLevelChildren',
'ParentOnly', 'ChildrenOnly'
:type search: str
:param filter: The filter parameter allows you to filter on the name
or display name fields. You can check for equality on the name field
(e.g. name eq '{entityName}') and you can check for substrings on
either the name or display name fields(e.g. contains(name,
'{substringToSearch}'), contains(displayName, '{substringToSearch')).
Note that the '{entityName}' and '{substringToSearch}' fields are
checked case insensitively.
:type filter: str
:param view: The view parameter allows clients to filter the type of
data that is returned by the getEntities call. Possible values
include: 'FullHierarchy', 'GroupsOnly', 'SubscriptionsOnly', 'Audit'
:type view: str
:param group_name: A filter which allows the get entities call to
focus on a particular group (i.e. "$filter=name eq 'groupName'")
:type group_name: str
:param cache_control: Indicates that the request shouldn't utilize any
caches.
:type cache_control: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of EntityInfo
:rtype:
~azure.mgmt.managementgroups.models.EntityInfoPaged[~azure.mgmt.managementgroups.models.EntityInfo]
:raises:
:class:`ErrorResponseException<azure.mgmt.managementgroups.models.ErrorResponseException>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = self.list.metadata['url']
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
if skiptoken is not None:
query_parameters['$skiptoken'] = self._serialize.query("skiptoken", skiptoken, 'str')
if skip is not None:
query_parameters['$skip'] = self._serialize.query("skip", skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int')
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, 'str')
if search is not None:
query_parameters['$search'] = self._serialize.query("search", search, 'str')
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if view is not None:
query_parameters['$view'] = self._serialize.query("view", view, 'str')
if group_name is not None:
query_parameters['groupName'] = self._serialize.query("group_name", group_name, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if cache_control is not None:
header_parameters['Cache-Control'] = self._serialize.header("cache_control", cache_control, 'str')
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
return response
# Deserialize response
deserialized = models.EntityInfoPaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.EntityInfoPaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
|
A job Id will be returned for the content posted on this endpoint. Once the content is evaluated against the Workflow provided the review will be created or ignored based on the workflow expression. <h3 > CallBack Schemas </ h3 > <p > <h4 > Job Completion CallBack Sample</ h4 > <br/ > { <br/ > JobId: <Job Id > <br/ > ReviewId: <Review Id if the Job resulted in a Review to be created > <br/ > WorkFlowId: default <br/ > Status: <This will be one of Complete InProgress Error > <br/ > ContentType: Image <br/ > ContentId: <This is the ContentId that was specified on input > <br/ > CallBackType: Job <br/ > Metadata: { <br/ > adultscore: 0. xxx <br/ > a: False <br/ > racyscore: 0. xxx <br/ > r: True <br/ > } <br/ > } <br/ > </ p > <p > <h4 > Review Completion CallBack Sample</ h4 > <br/ > { ReviewId: <Review Id > <br/ > ModifiedOn: 2016 - 10 - 11T22: 36: 32. 9934851Z <br/ > ModifiedBy: <Name of the Reviewer > <br/ > CallBackType: Review <br/ > ContentId: <The ContentId that was specified input > <br/ > Metadata: { <br/ > adultscore: 0. xxx a: False <br/ > racyscore: 0. xxx <br/ > r: True <br/ > } <br/ > ReviewerResultTags: { <br/ > a: False <br/ > r: True <br/ > } <br/ > } <br/ > </ p >.
|
def create_job(
self, team_name, content_type, content_id, workflow_name, job_content_type, content_value, call_back_endpoint=None, custom_headers=None, raw=False, **operation_config):
"""A job Id will be returned for the content posted on this endpoint.
Once the content is evaluated against the Workflow provided the review
will be created or ignored based on the workflow expression.
<h3>CallBack Schemas </h3>
<p>
<h4>Job Completion CallBack Sample</h4><br/>
{<br/>
"JobId": "<Job Id>,<br/>
"ReviewId": "<Review Id, if the Job resulted in a Review to be
created>",<br/>
"WorkFlowId": "default",<br/>
"Status": "<This will be one of Complete, InProgress, Error>",<br/>
"ContentType": "Image",<br/>
"ContentId": "<This is the ContentId that was specified on
input>",<br/>
"CallBackType": "Job",<br/>
"Metadata": {<br/>
"adultscore": "0.xxx",<br/>
"a": "False",<br/>
"racyscore": "0.xxx",<br/>
"r": "True"<br/>
}<br/>
}<br/>
</p>
<p>
<h4>Review Completion CallBack Sample</h4><br/>
{
"ReviewId": "<Review Id>",<br/>
"ModifiedOn": "2016-10-11T22:36:32.9934851Z",<br/>
"ModifiedBy": "<Name of the Reviewer>",<br/>
"CallBackType": "Review",<br/>
"ContentId": "<The ContentId that was specified input>",<br/>
"Metadata": {<br/>
"adultscore": "0.xxx",
"a": "False",<br/>
"racyscore": "0.xxx",<br/>
"r": "True"<br/>
},<br/>
"ReviewerResultTags": {<br/>
"a": "False",<br/>
"r": "True"<br/>
}<br/>
}<br/>
</p>.
:param team_name: Your team name.
:type team_name: str
:param content_type: Image, Text or Video. Possible values include:
'Image', 'Text', 'Video'
:type content_type: str
:param content_id: Id/Name to identify the content submitted.
:type content_id: str
:param workflow_name: Workflow Name that you want to invoke.
:type workflow_name: str
:param job_content_type: The content type. Possible values include:
'application/json', 'image/jpeg'
:type job_content_type: str
:param content_value: Content to evaluate for a job.
:type content_value: str
:param call_back_endpoint: Callback endpoint for posting the create
job result.
:type call_back_endpoint: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: JobId or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.vision.contentmoderator.models.JobId
or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.contentmoderator.models.APIErrorException>`
"""
content = models.Content(content_value=content_value)
# Construct URL
url = self.create_job.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'teamName': self._serialize.url("team_name", team_name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['ContentType'] = self._serialize.query("content_type", content_type, 'str')
query_parameters['ContentId'] = self._serialize.query("content_id", content_id, 'str')
query_parameters['WorkflowName'] = self._serialize.query("workflow_name", workflow_name, 'str')
if call_back_endpoint is not None:
query_parameters['CallBackEndpoint'] = self._serialize.query("call_back_endpoint", call_back_endpoint, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
header_parameters['Content-Type'] = self._serialize.header("job_content_type", job_content_type, 'str')
# Construct body
body_content = self._serialize.body(content, 'Content')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('JobId', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
Get a client for a queue entity.
|
def get_queue(self, queue_name):
"""Get a client for a queue entity.
:param queue_name: The name of the queue.
:type queue_name: str
:rtype: ~azure.servicebus.servicebus_client.QueueClient
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
:raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START get_queue_client]
:end-before: [END get_queue_client]
:language: python
:dedent: 8
:caption: Get the specific queue client from Service Bus client
"""
try:
queue = self.mgmt_client.get_queue(queue_name)
except requests.exceptions.ConnectionError as e:
raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
except AzureServiceBusResourceNotFound:
raise ServiceBusResourceNotFound("Specificed queue does not exist.")
return QueueClient.from_entity(
self._get_host(), queue,
shared_access_key_name=self.shared_access_key_name,
shared_access_key_value=self.shared_access_key_value,
mgmt_client=self.mgmt_client,
debug=self.debug)
|
Get clients for all queue entities in the namespace.
|
def list_queues(self):
"""Get clients for all queue entities in the namespace.
:rtype: list[~azure.servicebus.servicebus_client.QueueClient]
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START list_queues]
:end-before: [END list_queues]
:language: python
:dedent: 4
:caption: List the queues from Service Bus client
"""
try:
queues = self.mgmt_client.list_queues()
except requests.exceptions.ConnectionError as e:
raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
queue_clients = []
for queue in queues:
queue_clients.append(QueueClient.from_entity(
self._get_host(), queue,
shared_access_key_name=self.shared_access_key_name,
shared_access_key_value=self.shared_access_key_value,
mgmt_client=self.mgmt_client,
debug=self.debug))
return queue_clients
|
Get a client for a topic entity.
|
def get_topic(self, topic_name):
"""Get a client for a topic entity.
:param topic_name: The name of the topic.
:type topic_name: str
:rtype: ~azure.servicebus.servicebus_client.TopicClient
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
:raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START get_topic_client]
:end-before: [END get_topic_client]
:language: python
:dedent: 8
:caption: Get the specific topic client from Service Bus client
"""
try:
topic = self.mgmt_client.get_topic(topic_name)
except requests.exceptions.ConnectionError as e:
raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
except AzureServiceBusResourceNotFound:
raise ServiceBusResourceNotFound("Specificed topic does not exist.")
return TopicClient.from_entity(
self._get_host(), topic,
shared_access_key_name=self.shared_access_key_name,
shared_access_key_value=self.shared_access_key_value,
debug=self.debug)
|
Get a client for all topic entities in the namespace.
|
def list_topics(self):
"""Get a client for all topic entities in the namespace.
:rtype: list[~azure.servicebus.servicebus_client.TopicClient]
:raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START list_topics]
:end-before: [END list_topics]
:language: python
:dedent: 4
:caption: List the topics from Service Bus client
"""
try:
topics = self.mgmt_client.list_topics()
except requests.exceptions.ConnectionError as e:
raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e)
topic_clients = []
for topic in topics:
topic_clients.append(TopicClient.from_entity(
self._get_host(), topic,
shared_access_key_name=self.shared_access_key_name,
shared_access_key_value=self.shared_access_key_value,
debug=self.debug))
return topic_clients
|
Browse messages currently pending in the queue.
|
def peek(self, count=1, start_from=0, session=None, **kwargs):
"""Browse messages currently pending in the queue.
Peeked messages are not removed from queue, nor are they locked. They cannot be completed,
deferred or dead-lettered.
:param count: The maximum number of messages to try and peek. The default
value is 1.
:type count: int
:param start_from: A message sequence number from which to start browsing messages.
:type start_from: int
:param session: If the entity requires sessions, a session ID must be supplied
in order that only messages from that session will be browsed. If the entity
does not require sessions this value will be ignored.
:type session: str
:rtype: list[~azure.servicebus.common.message.PeekMessage]
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START peek_messages_service_bus]
:end-before: [END peek_messages_service_bus]
:language: python
:dedent: 4
:caption: Look at specificied number of messages without removing them from queue
"""
message = {'from-sequence-number': types.AMQPLong(start_from), 'message-count': int(count)}
if self.entity and self.requires_session:
if not session:
raise ValueError("Sessions are required, please set session.")
message['session-id'] = session
with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
return handler._mgmt_request_response( # pylint: disable=protected-access
REQUEST_RESPONSE_PEEK_OPERATION,
message,
mgmt_handlers.peek_op)
|
List session IDs.
|
def list_sessions(self, updated_since=None, max_results=100, skip=0, **kwargs):
"""List session IDs.
List the Session IDs with pending messages in the queue where the state of the session
has been updated since the timestamp provided. If no timestamp is provided, all will be returned.
If the state of a session has never been set, it will not be returned regardless of whether
there are messages pending.
:param updated_since: The UTC datetime from which to return updated pending Session IDs.
:type updated_since: datetime.datetime
:param max_results: The maximum number of Session IDs to return. Default value is 100.
:type max_results: int
:param skip: The page value to jump to. Default value is 0.
:type skip: int
:rtype: list[str]
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START list_sessions_service_bus]
:end-before: [END list_sessions_service_bus]
:language: python
:dedent: 4
:caption: Get the Ids of session which have messages pending in the queue
"""
if self.entity and not self.requires_session:
raise ValueError("This is not a sessionful entity.")
message = {
'last-updated-time': updated_since or datetime.datetime.utcfromtimestamp(0),
'skip': types.AMQPInt(skip),
'top': types.AMQPInt(max_results),
}
with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
return handler._mgmt_request_response( # pylint: disable=protected-access
REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,
message,
mgmt_handlers.list_sessions_op)
|
Receive messages by sequence number that have been previously deferred.
|
def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock, **kwargs):
"""Receive messages by sequence number that have been previously deferred.
When receiving deferred messages from a partitioned entity, all of the supplied
sequence numbers must be messages from the same partition.
:param sequence_numbers: A list of the sequence numbers of messages that have been
deferred.
:type sequence_numbers: list[int]
:param mode: The mode with which messages will be retrieved from the entity. The two options
are PeekLock and ReceiveAndDelete. Messages received with PeekLock must be settled within a given
lock period before they will be removed from the queue. Messages received with ReceiveAndDelete
will be immediately removed from the queue, and cannot be subsequently rejected or re-received if
the client fails to process the message. The default mode is PeekLock.
:type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
:rtype: list[~azure.servicebus.common.message.Message]
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START receive_deferred_messages_service_bus]
:end-before: [END receive_deferred_messages_service_bus]
:language: python
:dedent: 8
:caption: Get the messages which were deferred using their sequence numbers
"""
if (self.entity and self.requires_session) or kwargs.get('session'):
raise ValueError("Sessionful deferred messages can only be received within a locked receive session.")
if not sequence_numbers:
raise ValueError("At least one sequence number must be specified.")
try:
receive_mode = mode.value.value
except AttributeError:
receive_mode = int(mode)
message = {
'sequence-numbers': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),
'receiver-settle-mode': types.AMQPuInt(receive_mode)}
mgmt_handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode)
with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
return handler._mgmt_request_response( # pylint: disable=protected-access
REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,
message,
mgmt_handler)
|
Settle messages that have been previously deferred.
|
def settle_deferred_messages(self, settlement, messages, **kwargs):
"""Settle messages that have been previously deferred.
:param settlement: How the messages are to be settled. This must be a string
of one of the following values: 'completed', 'suspended', 'abandoned'.
:type settlement: str
:param messages: A list of deferred messages to be settled.
:type messages: list[~azure.servicebus.common.message.DeferredMessage]
Example:
.. literalinclude:: ../examples/test_examples.py
:start-after: [START settle_deferred_messages_service_bus]
:end-before: [END settle_deferred_messages_service_bus]
:language: python
:dedent: 8
:caption: Settle deferred messages.
"""
if (self.entity and self.requires_session) or kwargs.get('session'):
raise ValueError("Sessionful deferred messages can only be settled within a locked receive session.")
if settlement.lower() not in ['completed', 'suspended', 'abandoned']:
raise ValueError("Settlement must be one of: 'completed', 'suspended', 'abandoned'")
if not messages:
raise ValueError("At least one message must be specified.")
message = {
'disposition-status': settlement.lower(),
'lock-tokens': types.AMQPArray([m.lock_token for m in messages])}
with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:
return handler._mgmt_request_response( # pylint: disable=protected-access
REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,
message,
mgmt_handlers.default)
|
List the web sites defined on this webspace.
|
def get_site(self, webspace_name, website_name):
'''
List the web sites defined on this webspace.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_get(self._get_sites_details_path(webspace_name,
website_name),
Site)
|
Create a website.
|
def create_site(self, webspace_name, website_name, geo_region, host_names,
plan='VirtualDedicatedPlan', compute_mode='Shared',
server_farm=None, site_mode=None):
'''
Create a website.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
geo_region:
The geographical region of the webspace that will be created.
host_names:
An array of fully qualified domain names for website. Only one
hostname can be specified in the azurewebsites.net domain.
The hostname should match the name of the website. Custom domains
can only be specified for Shared or Standard websites.
plan:
This value must be 'VirtualDedicatedPlan'.
compute_mode:
This value should be 'Shared' for the Free or Paid Shared
offerings, or 'Dedicated' for the Standard offering. The default
value is 'Shared'. If you set it to 'Dedicated', you must specify
a value for the server_farm parameter.
server_farm:
The name of the Server Farm associated with this website. This is
a required value for Standard mode.
site_mode:
Can be None, 'Limited' or 'Basic'. This value is 'Limited' for the
Free offering, and 'Basic' for the Paid Shared offering. Standard
mode does not use the site_mode parameter; it uses the compute_mode
parameter.
'''
xml = _XmlSerializer.create_website_to_xml(webspace_name, website_name, geo_region, plan, host_names, compute_mode, server_farm, site_mode)
return self._perform_post(
self._get_sites_path(webspace_name),
xml,
Site)
|
Delete a website.
|
def delete_site(self, webspace_name, website_name,
delete_empty_server_farm=False, delete_metrics=False):
'''
Delete a website.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
delete_empty_server_farm:
If the site being deleted is the last web site in a server farm,
you can delete the server farm by setting this to True.
delete_metrics:
To also delete the metrics for the site that you are deleting, you
can set this to True.
'''
path = self._get_sites_details_path(webspace_name, website_name)
query = ''
if delete_empty_server_farm:
query += '&deleteEmptyServerFarm=true'
if delete_metrics:
query += '&deleteMetrics=true'
if query:
path = path + '?' + query.lstrip('&')
return self._perform_delete(path)
|
Update a web site.
|
def update_site(self, webspace_name, website_name, state=None):
'''
Update a web site.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
state:
The wanted state ('Running' or 'Stopped' accepted)
'''
xml = _XmlSerializer.update_website_to_xml(state)
return self._perform_put(
self._get_sites_details_path(webspace_name, website_name),
xml, as_async=True)
|
Restart a web site.
|
def restart_site(self, webspace_name, website_name):
'''
Restart a web site.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_post(
self._get_restart_path(webspace_name, website_name),
None, as_async=True)
|
Get historical usage metrics.
|
def get_historical_usage_metrics(self, webspace_name, website_name,
metrics = None, start_time=None, end_time=None, time_grain=None):
'''
Get historical usage metrics.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
metrics:
Optional. List of metrics name. Otherwise, all metrics returned.
start_time:
Optional. An ISO8601 date. Otherwise, current hour is used.
end_time:
Optional. An ISO8601 date. Otherwise, current time is used.
time_grain:
Optional. A rollup name, as P1D. OTherwise, default rollup for the metrics is used.
More information and metrics name at:
http://msdn.microsoft.com/en-us/library/azure/dn166964.aspx
'''
metrics = ('names='+','.join(metrics)) if metrics else ''
start_time = ('StartTime='+start_time) if start_time else ''
end_time = ('EndTime='+end_time) if end_time else ''
time_grain = ('TimeGrain='+time_grain) if time_grain else ''
parameters = ('&'.join(v for v in (metrics, start_time, end_time, time_grain) if v))
parameters = '?'+parameters if parameters else ''
return self._perform_get(self._get_historical_usage_metrics_path(webspace_name, website_name) + parameters,
MetricResponses)
|
Get metric definitions of metrics available of this web site.
|
def get_metric_definitions(self, webspace_name, website_name):
'''
Get metric definitions of metrics available of this web site.
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_get(self._get_metric_definitions_path(webspace_name, website_name),
MetricDefinitions)
|
Get a site s publish profile as a string
|
def get_publish_profile_xml(self, webspace_name, website_name):
'''
Get a site's publish profile as a string
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
None).body.decode("utf-8")
|
Get a site s publish profile as an object
|
def get_publish_profile(self, webspace_name, website_name):
'''
Get a site's publish profile as an object
webspace_name:
The name of the webspace.
website_name:
The name of the website.
'''
return self._perform_get(self._get_publishxml_path(webspace_name, website_name),
PublishData)
|
Adds authorization header and encrypts and signs the request if supported on the specific request.: param request: unprotected request to apply security protocol: return: protected request with appropriate security protocal applied
|
def protect_request(self, request):
"""
Adds authorization header, and encrypts and signs the request if supported on the specific request.
:param request: unprotected request to apply security protocol
:return: protected request with appropriate security protocal applied
"""
# Setup the auth header on the request
# Due to limitations in the service we hard code the auth scheme to 'Bearer' as the service will fail with any
# other scheme or a different casing such as 'bearer', once this is fixed the following line should be replaced:
# request.headers['Authorization'] = '{} {}'.format(auth[0], auth[1])
request.headers['Authorization'] = '{} {}'.format('Bearer', self.client_security_token)
# if the current message security doesn't support message protection, or the body is empty
# skip protection and return the original request
if not self.supports_protection() or len(request.body) == 0:
return request
plain_text = request.body
# if the client encryption key is specified add it to the body of the request
if self.client_encryption_key:
# note that this assumes that the body is already json and not simple string content
# this is true for all requests which currently support message encryption, but might
# need to be revisited when the types of
body_dict = json.loads(plain_text)
body_dict['rek'] = {'jwk': self.client_encryption_key.to_jwk().serialize()}
plain_text = json.dumps(body_dict).encode(encoding='utf8')
# build the header for the jws body
jws_header = _JwsHeader()
jws_header.alg = 'RS256'
jws_header.kid = self.client_signature_key.kid
jws_header.at = self.client_security_token
jws_header.ts = int(time.time())
jws_header.typ = 'PoP'
jws = _JwsObject()
jws.protected = jws_header.to_compact_header()
jws.payload = self._protect_payload(plain_text)
data = (jws.protected + '.' + jws.payload).encode('ascii')
jws.signature = _bstr_to_b64url(self.client_signature_key.sign(data))
request.headers['Content-Type'] = 'application/jose+json'
request.prepare_body(data=jws.to_flattened_jws(), files=None)
return request
|
Removes protection from the specified response: param request: response from the key vault service: return: unprotected response with any security protocal encryption removed
|
def unprotect_response(self, response, **kwargs):
"""
Removes protection from the specified response
:param request: response from the key vault service
:return: unprotected response with any security protocal encryption removed
"""
body = response.content
# if the current message security doesn't support message protection, the body is empty, or the request failed
# skip protection and return the original response
if not self.supports_protection() or len(response.content) == 0 or response.status_code != 200:
return response
# ensure the content-type is application/jose+json
if 'application/jose+json' not in response.headers.get('content-type', '').lower():
raise ValueError('Invalid protected response')
# deserialize the response into a JwsObject, using response.text so requests handles the encoding
jws = _JwsObject().deserialize(body)
# deserialize the protected header
jws_header = _JwsHeader.from_compact_header(jws.protected)
# ensure the jws signature kid matches the key from original challenge
# and the alg matches expected signature alg
if jws_header.kid != self.server_signature_key.kid \
or jws_header.alg != 'RS256':
raise ValueError('Invalid protected response')
# validate the signature of the jws
data = (jws.protected + '.' + jws.payload).encode('ascii')
# verify will raise an InvalidSignature exception if the signature doesn't match
self.server_signature_key.verify(signature=_b64_to_bstr(jws.signature), data=data)
# get the unprotected response body
decrypted = self._unprotect_payload(jws.payload)
response._content = decrypted
response.headers['Content-Type'] = 'application/json'
return response
|
Determines if the the current HttpMessageSecurity object supports the message protection protocol.: return: True if the current object supports protection otherwise False
|
def supports_protection(self):
"""
Determines if the the current HttpMessageSecurity object supports the message protection protocol.
:return: True if the current object supports protection, otherwise False
"""
return self.client_signature_key \
and self.client_encryption_key \
and self.server_signature_key \
and self.server_encryption_key
|
Updates the policies for the specified container registry.
|
def update_policies(
self, resource_group_name, registry_name, quarantine_policy=None, trust_policy=None, custom_headers=None, raw=False, polling=True, **operation_config):
"""Updates the policies for the specified container registry.
:param resource_group_name: The name of the resource group to which
the container registry belongs.
:type resource_group_name: str
:param registry_name: The name of the container registry.
:type registry_name: str
:param quarantine_policy: An object that represents quarantine policy
for a container registry.
:type quarantine_policy:
~azure.mgmt.containerregistry.v2018_02_01_preview.models.QuarantinePolicy
:param trust_policy: An object that represents content trust policy
for a container registry.
:type trust_policy:
~azure.mgmt.containerregistry.v2018_02_01_preview.models.TrustPolicy
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns RegistryPolicies or
ClientRawResponse<RegistryPolicies> if raw==True
:rtype:
~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies]
or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.containerregistry.v2018_02_01_preview.models.RegistryPolicies]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._update_policies_initial(
resource_group_name=resource_group_name,
registry_name=registry_name,
quarantine_policy=quarantine_policy,
trust_policy=trust_policy,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
deserialized = self._deserialize('RegistryPolicies', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
|
The Create Cloud Service request creates a new cloud service. When job collections are created they are hosted within a cloud service. A cloud service groups job collections together in a given region. Once a cloud service has been created job collections can then be created and contained within it.
|
def create_cloud_service(self, cloud_service_id, label, description, geo_region):
'''
The Create Cloud Service request creates a new cloud service. When job
collections are created, they are hosted within a cloud service.
A cloud service groups job collections together in a given region.
Once a cloud service has been created, job collections can then be
created and contained within it.
cloud_service_id:
The cloud service id
label:
The name of the cloud service.
description:
The description of the cloud service.
geo_region:
The geographical region of the webspace that will be created.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('label', label)
_validate_not_none('description', description)
_validate_not_none('geo_region', geo_region)
path = self._get_cloud_services_path(cloud_service_id)
body = _SchedulerManagementXmlSerializer.create_cloud_service_to_xml(
label, description, geo_region)
return self._perform_put(path, body, as_async=True)
|
The Get Cloud Service operation gets all the resources ( job collections ) in the cloud service.
|
def get_cloud_service(self, cloud_service_id):
'''
The Get Cloud Service operation gets all the resources (job collections)
in the cloud service.
cloud_service_id:
The cloud service id
'''
_validate_not_none('cloud_service_id', cloud_service_id)
path = self._get_cloud_services_path(cloud_service_id)
return self._perform_get(path, CloudService)
|
The Get Cloud Service operation gets all the resources ( job collections ) in the cloud service.
|
def delete_cloud_service(self, cloud_service_id):
'''
The Get Cloud Service operation gets all the resources (job collections)
in the cloud service.
cloud_service_id:
The cloud service id
'''
_validate_not_none('cloud_service_id', cloud_service_id)
path = self._get_cloud_services_path(cloud_service_id)
return self._perform_delete(path, as_async=True)
|
The Check Name Availability operation checks if a new job collection with the given name may be created or if it is unavailable. The result of the operation is a Boolean true or false.
|
def check_job_collection_name(self, cloud_service_id, job_collection_id):
'''
The Check Name Availability operation checks if a new job collection with
the given name may be created, or if it is unavailable. The result of the
operation is a Boolean true or false.
cloud_service_id:
The cloud service id
job_collection_id:
The name of the job_collection_id.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
path = self._get_cloud_services_path(
cloud_service_id, "scheduler", "jobCollections")
path += "?op=checknameavailability&resourceName=" + job_collection_id
return self._perform_post(path, None, AvailabilityResponse)
|
The Create Job Collection request is specified as follows. Replace <subscription - id > with your subscription ID <cloud - service - id > with your cloud service ID and <job - collection - id > with the ID of the job collection you \ d like to create. There are no default pre - existing job collections every job collection must be manually created.
|
def create_job_collection(self, cloud_service_id, job_collection_id, plan="Standard"):
'''
The Create Job Collection request is specified as follows. Replace <subscription-id>
with your subscription ID, <cloud-service-id> with your cloud service ID, and
<job-collection-id> with the ID of the job collection you\'d like to create.
There are no "default" pre-existing job collections every job collection
must be manually created.
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
path = self._get_cloud_services_path(
cloud_service_id, "scheduler", "jobCollections")
path += '/' + _str(job_collection_id)
body = _SchedulerManagementXmlSerializer.create_job_collection_to_xml(
plan)
return self._perform_put(path, body, as_async=True)
|
The Delete Job Collection request is specified as follows. Replace <subscription - id > with your subscription ID <cloud - service - id > with your cloud service ID and <job - collection - id > with the ID of the job collection you \ d like to delete.
|
def delete_job_collection(self, cloud_service_id, job_collection_id):
'''
The Delete Job Collection request is specified as follows. Replace <subscription-id>
with your subscription ID, <cloud-service-id> with your cloud service ID, and
<job-collection-id> with the ID of the job collection you\'d like to delete.
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
path = self._get_cloud_services_path(
cloud_service_id, "scheduler", "jobCollections")
path += '/' + _str(job_collection_id)
return self._perform_delete(path, as_async=True)
|
The Get Job Collection operation gets the details of a job collection
|
def get_job_collection(self, cloud_service_id, job_collection_id):
'''
The Get Job Collection operation gets the details of a job collection
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
path = self._get_job_collection_path(
cloud_service_id, job_collection_id)
return self._perform_get(path, Resource)
|
The Create Job request creates a new job. cloud_service_id: The cloud service id job_collection_id: Name of the hosted service. job_id: The job id you wish to create. job: A dictionary of the payload
|
def create_job(self, cloud_service_id, job_collection_id, job_id, job):
'''
The Create Job request creates a new job.
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
job_id:
The job id you wish to create.
job:
A dictionary of the payload
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
_validate_not_none('job_id', job_id)
_validate_not_none('job', job)
path = self._get_job_collection_path(
cloud_service_id, job_collection_id, job_id)
self.content_type = "application/json"
return self._perform_put(path, JSONEncoder().encode(job), as_async=True)
|
The Delete Job request creates a new job. cloud_service_id: The cloud service id job_collection_id: Name of the hosted service. job_id: The job id you wish to create.
|
def delete_job(self, cloud_service_id, job_collection_id, job_id):
'''
The Delete Job request creates a new job.
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
job_id:
The job id you wish to create.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
_validate_not_none('job_id', job_id)
path = self._get_job_collection_path(
cloud_service_id, job_collection_id, job_id)
return self._perform_delete(path, as_async=True)
|
The Get Job operation gets the details ( including the current job status ) of the specified job from the specified job collection.
|
def get_job(self, cloud_service_id, job_collection_id, job_id):
'''
The Get Job operation gets the details (including the current job status)
of the specified job from the specified job collection.
The return type is
cloud_service_id:
The cloud service id
job_collection_id:
Name of the hosted service.
job_id:
The job id you wish to create.
'''
_validate_not_none('cloud_service_id', cloud_service_id)
_validate_not_none('job_collection_id', job_collection_id)
_validate_not_none('job_id', job_id)
path = self._get_job_collection_path(
cloud_service_id, job_collection_id, job_id)
self.content_type = "application/json"
payload = self._perform_get(path).body.decode()
return json.loads(payload)
|
Completes the restore operation on a managed database.
|
def complete_restore(
self, location_name, operation_id, last_backup_name, custom_headers=None, raw=False, polling=True, **operation_config):
"""Completes the restore operation on a managed database.
:param location_name: The name of the region where the resource is
located.
:type location_name: str
:param operation_id: Management operation id that this request tries
to complete.
:type operation_id: str
:param last_backup_name: The last backup name to apply
:type last_backup_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: The poller return type is ClientRawResponse, the
direct response alongside the deserialized response
:param polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:return: An instance of LROPoller that returns None or
ClientRawResponse<None> if raw==True
:rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
raw_result = self._complete_restore_initial(
location_name=location_name,
operation_id=operation_id,
last_backup_name=last_backup_name,
custom_headers=custom_headers,
raw=True,
**operation_config
)
def get_long_running_output(response):
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
lro_delay = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
|
Module depends on the API version: * 2016 - 10 - 01:: mod: v2016_10_01. models<azure. keyvault. v2016_10_01. models > * 7. 0:: mod: v7_0. models<azure. keyvault. v7_0. models >
|
def models(self):
"""Module depends on the API version:
* 2016-10-01: :mod:`v2016_10_01.models<azure.keyvault.v2016_10_01.models>`
* 7.0: :mod:`v7_0.models<azure.keyvault.v7_0.models>`
"""
api_version = self._get_api_version(None)
if api_version == v7_0_VERSION:
from azure.keyvault.v7_0 import models as implModels
elif api_version == v2016_10_01_VERSION:
from azure.keyvault.v2016_10_01 import models as implModels
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
return implModels
|
Get the versioned client implementation corresponding to the current profile.: return: The versioned client implementation.
|
def _get_client_impl(self):
"""
Get the versioned client implementation corresponding to the current profile.
:return: The versioned client implementation.
"""
api_version = self._get_api_version(None)
if api_version not in self._client_impls:
self._create_client_impl(api_version)
return self._client_impls[api_version]
|
Creates the client implementation corresponding to the specifeid api_version.: param api_version:: return:
|
def _create_client_impl(self, api_version):
"""
Creates the client implementation corresponding to the specifeid api_version.
:param api_version:
:return:
"""
if api_version == v7_0_VERSION:
from azure.keyvault.v7_0 import KeyVaultClient as ImplClient
elif api_version == v2016_10_01_VERSION:
from azure.keyvault.v2016_10_01 import KeyVaultClient as ImplClient
else:
raise NotImplementedError("APIVersion {} is not available".format(api_version))
impl = ImplClient(credentials=self._credentials)
impl.config = self.config
# if __enter__ has previously been called and the impl client has __enter__ defined we need to call it
if self._entered and hasattr(impl, '__enter__'):
impl.__enter__()
self._client_impls[api_version] = impl
return impl
|
Send one or more messages to be enqueued at a specific time.
|
async def schedule(self, schedule_time, *messages):
"""Send one or more messages to be enqueued at a specific time.
Returns a list of the sequence numbers of the enqueued messages.
:param schedule_time: The date and time to enqueue the messages.
:type schedule_time: ~datetime.datetime
:param messages: The messages to schedule.
:type messages: ~azure.servicebus.aio.async_message.Message
:rtype: list[int]
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START schedule_messages]
:end-before: [END schedule_messages]
:language: python
:dedent: 4
:caption: Schedule messages.
"""
if not self.running:
await self.open()
request_body = self._build_schedule_request(schedule_time, *messages)
return await self._mgmt_request_response(
REQUEST_RESPONSE_SCHEDULE_MESSAGE_OPERATION,
request_body,
mgmt_handlers.schedule_op)
|
Cancel one or more messages that have previsouly been scheduled and are still pending.
|
async def cancel_scheduled_messages(self, *sequence_numbers):
"""Cancel one or more messages that have previsouly been scheduled and are still pending.
:param sequence_numbers: The seqeuence numbers of the scheduled messages.
:type sequence_numbers: int
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START cancel_schedule_messages]
:end-before: [END cancel_schedule_messages]
:language: python
:dedent: 4
:caption: Schedule messages.
"""
if not self.running:
await self.open()
numbers = [types.AMQPLong(s) for s in sequence_numbers]
request_body = {'sequence-numbers': types.AMQPArray(numbers)}
return await self._mgmt_request_response(
REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION,
request_body,
mgmt_handlers.default)
|
Wait until all pending messages have been sent.
|
async def send_pending_messages(self):
"""Wait until all pending messages have been sent.
:returns: A list of the send results of all the pending messages. Each
send result is a tuple with two values. The first is a boolean, indicating `True`
if the message sent, or `False` if it failed. The second is an error if the message
failed, otherwise it will be `None`.
:rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]]
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START queue_sender_messages]
:end-before: [END queue_sender_messages]
:language: python
:dedent: 4
:caption: Schedule messages.
"""
if not self.running:
await self.open()
try:
pending = self._handler._pending_messages[:] # pylint: disable=protected-access
await self._handler.wait_async()
results = []
for m in pending:
if m.state == constants.MessageState.SendFailed:
results.append((False, MessageSendFailed(m._response))) # pylint: disable=protected-access
else:
results.append((True, None))
return results
except Exception as e: # pylint: disable=broad-except
raise MessageSendFailed(e)
|
Reconnect the handler.
|
async def reconnect(self):
"""Reconnect the handler.
If the handler was disconnected from the service with
a retryable error - attempt to reconnect.
This method will be called automatically for most retryable errors.
Also attempts to re-queue any messages that were pending before the reconnect.
"""
unsent_events = self._handler.pending_messages
await super(Sender, self).reconnect()
try:
self._handler.queue_message(*unsent_events)
await self._handler.wait_async()
except Exception as e: # pylint: disable=broad-except
await self._handle_exception(e)
|
Send a message and blocks until acknowledgement is received or the operation fails.
|
async def send(self, message):
"""Send a message and blocks until acknowledgement is received or the operation fails.
If neither the Sender nor the message has a session ID, a `ValueError` will be raised.
:param message: The message to be sent.
:type message: ~azure.servicebus.aio.async_message.Message
:raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
send.
Example:
.. literalinclude:: ../examples/async_examples/test_examples_async.py
:start-after: [START open_close_session_sender_context]
:end-before: [END open_close_session_sender_context]
:language: python
:dedent: 4
:caption: Open a sessionful Sender and send messages.
"""
if not isinstance(message, Message):
raise TypeError("Value of message must be of type 'Message'.")
if not self.session_id and not message.properties.group_id:
raise ValueError("Message must have Session ID.")
return await super(SessionSender, self).send(message)
|
Writes a certificate file to the specified location. This can then be used to instantiate ServiceManagementService. Returns the subscription ID.
|
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None):
'''
Writes a certificate file to the specified location. This can then be used
to instantiate ServiceManagementService. Returns the subscription ID.
publish_settings_path:
Path to subscription file downloaded from
http://go.microsoft.com/fwlink/?LinkID=301775
path_to_write_certificate:
Path to write the certificate file.
subscription_id:
(optional) Provide a subscription id here if you wish to use a
specific subscription under the publish settings file.
'''
import base64
try:
from xml.etree import cElementTree as ET
except ImportError:
from xml.etree import ElementTree as ET
try:
import OpenSSL.crypto as crypto
except:
raise Exception("pyopenssl is required to use get_certificate_from_publish_settings")
_validate_not_none('publish_settings_path', publish_settings_path)
_validate_not_none('path_to_write_certificate', path_to_write_certificate)
# parse the publishsettings file and find the ManagementCertificate Entry
tree = ET.parse(publish_settings_path)
subscriptions = tree.getroot().findall("./PublishProfile/Subscription")
# Default to the first subscription in the file if they don't specify
# or get the matching subscription or return none.
if subscription_id:
subscription = next((s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None)
else:
subscription = subscriptions[0]
# validate that subscription was found
if subscription is None:
raise ValueError("The provided subscription_id '{}' was not found in the publish settings file provided at '{}'".format(subscription_id, publish_settings_path))
cert_string = _decode_base64_to_bytes(subscription.get('ManagementCertificate'))
# Load the string in pkcs12 format. Don't provide a password as it isn't encrypted.
cert = crypto.load_pkcs12(cert_string, b'')
# Write the data out as a PEM format to a random location in temp for use under this run.
with open(path_to_write_certificate, 'wb') as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate()))
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey()))
return subscription.get('Id')
|
The Web Search API lets you send a search query to Bing and get back search results that include links to webpages images and more.
|
def search(
self, query, accept_language=None, pragma=None, user_agent=None, client_id=None, client_ip=None, location=None, answer_count=None, country_code=None, count=None, freshness=None, market="en-us", offset=None, promote=None, response_filter=None, safe_search=None, set_lang=None, text_decorations=None, text_format=None, custom_headers=None, raw=False, **operation_config):
"""The Web Search API lets you send a search query to Bing and get back
search results that include links to webpages, images, and more.
:param query: The user's search query term. The term may not be empty.
The term may contain Bing Advanced Operators. For example, to limit
results to a specific domain, use the site: operator.
:type query: str
:param accept_language: A comma-delimited list of one or more
languages to use for user interface strings. The list is in decreasing
order of preference. For additional information, including expected
format, see
[RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
This header and the setLang query parameter are mutually exclusive; do
not specify both. If you set this header, you must also specify the cc
query parameter. Bing will use the first supported language it finds
from the list, and combine that language with the cc parameter value
to determine the market to return results for. If the list does not
include a supported language, Bing will find the closest language and
market that supports the request, and may use an aggregated or default
market for the results instead of a specified one. You should use this
header and the cc query parameter only if you specify multiple
languages; otherwise, you should use the mkt and setLang query
parameters. A user interface string is a string that's used as a label
in a user interface. There are very few user interface strings in the
JSON response objects. Any links in the response objects to Bing.com
properties will apply the specified language.
:type accept_language: str
:param pragma: By default, Bing returns cached content, if available.
To prevent Bing from returning cached content, set the Pragma header
to no-cache (for example, Pragma: no-cache).
:type pragma: str
:param user_agent: The user agent originating the request. Bing uses
the user agent to provide mobile users with an optimized experience.
Although optional, you are strongly encouraged to always specify this
header. The user-agent should be the same string that any commonly
used browser would send. For information about user agents, see [RFC
2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
:type user_agent: str
:param client_id: Bing uses this header to provide users with
consistent behavior across Bing API calls. Bing often flights new
features and improvements, and it uses the client ID as a key for
assigning traffic on different flights. If you do not use the same
client ID for a user across multiple requests, then Bing may assign
the user to multiple conflicting flights. Being assigned to multiple
conflicting flights can lead to an inconsistent user experience. For
example, if the second request has a different flight assignment than
the first, the experience may be unexpected. Also, Bing can use the
client ID to tailor web results to that client ID’s search history,
providing a richer experience for the user. Bing also uses this header
to help improve result rankings by analyzing the activity generated by
a client ID. The relevance improvements help with better quality of
results delivered by Bing APIs and in turn enables higher
click-through rates for the API consumer. IMPORTANT: Although
optional, you should consider this header required. Persisting the
client ID across multiple requests for the same end user and device
combination enables 1) the API consumer to receive a consistent user
experience, and 2) higher click-through rates via better quality of
results from the Bing APIs. Each user that uses your application on
the device must have a unique, Bing generated client ID. If you do not
include this header in the request, Bing generates an ID and returns
it in the X-MSEdge-ClientID response header. The only time that you
should NOT include this header in a request is the first time the user
uses your app on that device. Use the client ID for each Bing API
request that your app makes for this user on the device. Persist the
client ID. To persist the ID in a browser app, use a persistent HTTP
cookie to ensure the ID is used across all sessions. Do not use a
session cookie. For other apps such as mobile apps, use the device's
persistent storage to persist the ID. The next time the user uses your
app on that device, get the client ID that you persisted. Bing
responses may or may not include this header. If the response includes
this header, capture the client ID and use it for all subsequent Bing
requests for the user on that device. If you include the
X-MSEdge-ClientID, you must not include cookies in the request.
:type client_id: str
:param client_ip: The IPv4 or IPv6 address of the client device. The
IP address is used to discover the user's location. Bing uses the
location information to determine safe search behavior. Although
optional, you are encouraged to always specify this header and the
X-Search-Location header. Do not obfuscate the address (for example,
by changing the last octet to 0). Obfuscating the address results in
the location not being anywhere near the device's actual location,
which may result in Bing serving erroneous results.
:type client_ip: str
:param location: A semicolon-delimited list of key/value pairs that
describe the client's geographical location. Bing uses the location
information to determine safe search behavior and to return relevant
local content. Specify the key/value pair as <key>:<value>. The
following are the keys that you use to specify the user's location.
lat (required): The latitude of the client's location, in degrees. The
latitude must be greater than or equal to -90.0 and less than or equal
to +90.0. Negative values indicate southern latitudes and positive
values indicate northern latitudes. long (required): The longitude of
the client's location, in degrees. The longitude must be greater than
or equal to -180.0 and less than or equal to +180.0. Negative values
indicate western longitudes and positive values indicate eastern
longitudes. re (required): The radius, in meters, which specifies the
horizontal accuracy of the coordinates. Pass the value returned by the
device's location service. Typical values might be 22m for GPS/Wi-Fi,
380m for cell tower triangulation, and 18,000m for reverse IP lookup.
ts (optional): The UTC UNIX timestamp of when the client was at the
location. (The UNIX timestamp is the number of seconds since January
1, 1970.) head (optional): The client's relative heading or direction
of travel. Specify the direction of travel as degrees from 0 through
360, counting clockwise relative to true north. Specify this key only
if the sp key is nonzero. sp (optional): The horizontal velocity
(speed), in meters per second, that the client device is traveling.
alt (optional): The altitude of the client device, in meters. are
(optional): The radius, in meters, that specifies the vertical
accuracy of the coordinates. Specify this key only if you specify the
alt key. Although many of the keys are optional, the more information
that you provide, the more accurate the location results are. Although
optional, you are encouraged to always specify the user's geographical
location. Providing the location is especially important if the
client's IP address does not accurately reflect the user's physical
location (for example, if the client uses VPN). For optimal results,
you should include this header and the X-MSEdge-ClientIP header, but
at a minimum, you should include this header.
:type location: str
:param answer_count: The number of answers that you want the response
to include. The answers that Bing returns are based on ranking. For
example, if Bing returns webpages, images, videos, and relatedSearches
for a request and you set this parameter to two (2), the response
includes webpages and images.If you included the responseFilter query
parameter in the same request and set it to webpages and news, the
response would include only webpages.
:type answer_count: int
:param country_code: A 2-character country code of the country where
the results come from. This API supports only the United States
market. If you specify this query parameter, it must be set to us. If
you set this parameter, you must also specify the Accept-Language
header. Bing uses the first supported language it finds from the
languages list, and combine that language with the country code that
you specify to determine the market to return results for. If the
languages list does not include a supported language, Bing finds the
closest language and market that supports the request, or it may use
an aggregated or default market for the results instead of a specified
one. You should use this query parameter and the Accept-Language query
parameter only if you specify multiple languages; otherwise, you
should use the mkt and setLang query parameters. This parameter and
the mkt query parameter are mutually exclusive—do not specify both.
:type country_code: str
:param count: The number of search results to return in the response.
The default is 10 and the maximum value is 50. The actual number
delivered may be less than requested.Use this parameter along with the
offset parameter to page results.For example, if your user interface
displays 10 search results per page, set count to 10 and offset to 0
to get the first page of results. For each subsequent page, increment
offset by 10 (for example, 0, 10, 20). It is possible for multiple
pages to include some overlap in results.
:type count: int
:param freshness: Filter search results by the following age values:
Day—Return webpages that Bing discovered within the last 24 hours.
Week—Return webpages that Bing discovered within the last 7 days.
Month—Return webpages that discovered within the last 30 days. This
filter applies only to webpage results and not to the other results
such as news and images. Possible values include: 'Day', 'Week',
'Month'
:type freshness: str or
~azure.cognitiveservices.search.websearch.models.Freshness
:param market: The market where the results come from. Typically, mkt
is the country where the user is making the request from. However, it
could be a different country if the user is not located in a country
where Bing delivers results. The market must be in the form <language
code>-<country code>. For example, en-US. The string is case
insensitive. If known, you are encouraged to always specify the
market. Specifying the market helps Bing route the request and return
an appropriate and optimal response. If you specify a market that is
not listed in Market Codes, Bing uses a best fit market code based on
an internal mapping that is subject to change. This parameter and the
cc query parameter are mutually exclusive—do not specify both.
:type market: str
:param offset: The zero-based offset that indicates the number of
search results to skip before returning results. The default is 0. The
offset should be less than (totalEstimatedMatches - count). Use this
parameter along with the count parameter to page results. For example,
if your user interface displays 10 search results per page, set count
to 10 and offset to 0 to get the first page of results. For each
subsequent page, increment offset by 10 (for example, 0, 10, 20). it
is possible for multiple pages to include some overlap in results.
:type offset: int
:param promote: A comma-delimited list of answers that you want the
response to include regardless of their ranking. For example, if you
set answerCount) to two (2) so Bing returns the top two ranked
answers, but you also want the response to include news, you'd set
promote to news. If the top ranked answers are webpages, images,
videos, and relatedSearches, the response includes webpages and images
because news is not a ranked answer. But if you set promote to video,
Bing would promote the video answer into the response and return
webpages, images, and videos. The answers that you want to promote do
not count against the answerCount limit. For example, if the ranked
answers are news, images, and videos, and you set answerCount to 1 and
promote to news, the response contains news and images. Or, if the
ranked answers are videos, images, and news, the response contains
videos and news. Possible values are Computation, Images, News,
RelatedSearches, SpellSuggestions, TimeZone, Videos, Webpages. Use
only if you specify answerCount.
:type promote: list[str or
~azure.cognitiveservices.search.websearch.models.AnswerType]
:param response_filter: A comma-delimited list of answers to include
in the response. If you do not specify this parameter, the response
includes all search answers for which there's relevant data. Possible
filter values are Computation, Images, News, RelatedSearches,
SpellSuggestions, TimeZone, Videos, Webpages. Although you may use
this filter to get a single answer, you should instead use the
answer-specific endpoint in order to get richer results. For example,
to receive only images, send the request to one of the Image Search
API endpoints. The RelatedSearches and SpellSuggestions answers do not
support a separate endpoint like the Image Search API does (only the
Web Search API returns them). To include answers that would otherwise
be excluded because of ranking, see the promote query parameter.
:type response_filter: list[str or
~azure.cognitiveservices.search.websearch.models.AnswerType]
:param safe_search: A filter used to filter adult content. Off: Return
webpages with adult text, images, or videos. Moderate: Return webpages
with adult text, but not adult images or videos. Strict: Do not return
webpages with adult text, images, or videos. The default is Moderate.
If the request comes from a market that Bing's adult policy requires
that safeSearch is set to Strict, Bing ignores the safeSearch value
and uses Strict. If you use the site: query operator, there is the
chance that the response may contain adult content regardless of what
the safeSearch query parameter is set to. Use site: only if you are
aware of the content on the site and your scenario supports the
possibility of adult content. Possible values include: 'Off',
'Moderate', 'Strict'
:type safe_search: str or
~azure.cognitiveservices.search.websearch.models.SafeSearch
:param set_lang: The language to use for user interface strings.
Specify the language using the ISO 639-1 2-letter language code. For
example, the language code for English is EN. The default is EN
(English). Although optional, you should always specify the language.
Typically, you set setLang to the same language specified by mkt
unless the user wants the user interface strings displayed in a
different language. This parameter and the Accept-Language header are
mutually exclusive; do not specify both. A user interface string is a
string that's used as a label in a user interface. There are few user
interface strings in the JSON response objects. Also, any links to
Bing.com properties in the response objects apply the specified
language.
:type set_lang: str
:param text_decorations: A Boolean value that determines whether
display strings should contain decoration markers such as hit
highlighting characters. If true, the strings may include markers. The
default is false. To specify whether to use Unicode characters or HTML
tags as the markers, see the textFormat query parameter.
:type text_decorations: bool
:param text_format: The type of markers to use for text decorations
(see the textDecorations query parameter). Possible values are Raw—Use
Unicode characters to mark content that needs special formatting. The
Unicode characters are in the range E000 through E019. For example,
Bing uses E000 and E001 to mark the beginning and end of query terms
for hit highlighting. HTML—Use HTML tags to mark content that needs
special formatting. For example, use <b> tags to highlight query terms
in display strings. The default is Raw. For display strings that
contain escapable HTML characters such as <, >, and &, if textFormat
is set to HTML, Bing escapes the characters as appropriate (for
example, < is escaped to <). Possible values include: 'Raw', 'Html'
:type text_format: str or
~azure.cognitiveservices.search.websearch.models.TextFormat
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: SearchResponse or ClientRawResponse if raw=true
:rtype:
~azure.cognitiveservices.search.websearch.models.SearchResponse or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.cognitiveservices.search.websearch.models.ErrorResponseException>`
"""
# Construct URL
url = self.search.metadata['url']
# Construct parameters
query_parameters = {}
if answer_count is not None:
query_parameters['answerCount'] = self._serialize.query("answer_count", answer_count, 'int')
if country_code is not None:
query_parameters['cc'] = self._serialize.query("country_code", country_code, 'str')
if count is not None:
query_parameters['count'] = self._serialize.query("count", count, 'int')
if freshness is not None:
query_parameters['freshness'] = self._serialize.query("freshness", freshness, 'str')
if market is not None:
query_parameters['mkt'] = self._serialize.query("market", market, 'str')
if offset is not None:
query_parameters['offset'] = self._serialize.query("offset", offset, 'int')
if promote is not None:
query_parameters['promote'] = self._serialize.query("promote", promote, '[str]', div=',')
query_parameters['q'] = self._serialize.query("query", query, 'str')
if response_filter is not None:
query_parameters['responseFilter'] = self._serialize.query("response_filter", response_filter, '[str]', div=',')
if safe_search is not None:
query_parameters['safeSearch'] = self._serialize.query("safe_search", safe_search, 'str')
if set_lang is not None:
query_parameters['setLang'] = self._serialize.query("set_lang", set_lang, 'str')
if text_decorations is not None:
query_parameters['textDecorations'] = self._serialize.query("text_decorations", text_decorations, 'bool')
if text_format is not None:
query_parameters['textFormat'] = self._serialize.query("text_format", text_format, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
header_parameters['X-BingApis-SDK'] = self._serialize.header("self.x_bing_apis_sdk", self.x_bing_apis_sdk, 'str')
if accept_language is not None:
header_parameters['Accept-Language'] = self._serialize.header("accept_language", accept_language, 'str')
if pragma is not None:
header_parameters['Pragma'] = self._serialize.header("pragma", pragma, 'str')
if user_agent is not None:
header_parameters['User-Agent'] = self._serialize.header("user_agent", user_agent, 'str')
if client_id is not None:
header_parameters['X-MSEdge-ClientID'] = self._serialize.header("client_id", client_id, 'str')
if client_ip is not None:
header_parameters['X-MSEdge-ClientIP'] = self._serialize.header("client_ip", client_ip, 'str')
if location is not None:
header_parameters['X-Search-Location'] = self._serialize.header("location", location, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('SearchResponse', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
The Custom Image Search API lets you send an image search query to Bing and get image results found in your custom view of the web.
|
def image_search(
self, custom_config, query, accept_language=None, user_agent=None, client_id=None, client_ip=None, location=None, aspect=None, color=None, country_code=None, count=None, freshness=None, height=None, id=None, image_content=None, image_type=None, license=None, market=None, max_file_size=None, max_height=None, max_width=None, min_file_size=None, min_height=None, min_width=None, offset=None, safe_search=None, size=None, set_lang=None, width=None, custom_headers=None, raw=False, **operation_config):
"""The Custom Image Search API lets you send an image search query to Bing
and get image results found in your custom view of the web.
:param custom_config: The identifier for the custom search
configuration
:type custom_config: long
:param query: The user's search query term. The term cannot be empty.
The term may contain [Bing Advanced
Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
example, to limit images to a specific domain, use the
[site:](http://msdn.microsoft.com/library/ff795613.aspx) operator. To
help improve relevance of an insights query (see
[insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)),
you should always include the user's query term. Use this parameter
only with the Image Search API.Do not specify this parameter when
calling the Trending Images API.
:type query: str
:param accept_language: A comma-delimited list of one or more
languages to use for user interface strings. The list is in decreasing
order of preference. For additional information, including expected
format, see
[RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
This header and the
[setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang)
query parameter are mutually exclusive; do not specify both. If you
set this header, you must also specify the
[cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc)
query parameter. To determine the market to return results for, Bing
uses the first supported language it finds from the list and combines
it with the cc parameter value. If the list does not include a
supported language, Bing finds the closest language and market that
supports the request or it uses an aggregated or default market for
the results. To determine the market that Bing used, see the
BingAPIs-Market header. Use this header and the cc query parameter
only if you specify multiple languages. Otherwise, use the
[mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt)
and
[setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#setlang)
query parameters. A user interface string is a string that's used as a
label in a user interface. There are few user interface strings in the
JSON response objects. Any links to Bing.com properties in the
response objects apply the specified language.
:type accept_language: str
:param user_agent: The user agent originating the request. Bing uses
the user agent to provide mobile users with an optimized experience.
Although optional, you are encouraged to always specify this header.
The user-agent should be the same string that any commonly used
browser sends. For information about user agents, see [RFC
2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
following are examples of user-agent strings. Windows Phone:
Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0
(Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD)
AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari /
533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X)
AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1
BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3;
WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0
(iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like
Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53
:type user_agent: str
:param client_id: Bing uses this header to provide users with
consistent behavior across Bing API calls. Bing often flights new
features and improvements, and it uses the client ID as a key for
assigning traffic on different flights. If you do not use the same
client ID for a user across multiple requests, then Bing may assign
the user to multiple conflicting flights. Being assigned to multiple
conflicting flights can lead to an inconsistent user experience. For
example, if the second request has a different flight assignment than
the first, the experience may be unexpected. Also, Bing can use the
client ID to tailor web results to that client ID’s search history,
providing a richer experience for the user. Bing also uses this header
to help improve result rankings by analyzing the activity generated by
a client ID. The relevance improvements help with better quality of
results delivered by Bing APIs and in turn enables higher
click-through rates for the API consumer. IMPORTANT: Although
optional, you should consider this header required. Persisting the
client ID across multiple requests for the same end user and device
combination enables 1) the API consumer to receive a consistent user
experience, and 2) higher click-through rates via better quality of
results from the Bing APIs. Each user that uses your application on
the device must have a unique, Bing generated client ID. If you do not
include this header in the request, Bing generates an ID and returns
it in the X-MSEdge-ClientID response header. The only time that you
should NOT include this header in a request is the first time the user
uses your app on that device. Use the client ID for each Bing API
request that your app makes for this user on the device. Persist the
client ID. To persist the ID in a browser app, use a persistent HTTP
cookie to ensure the ID is used across all sessions. Do not use a
session cookie. For other apps such as mobile apps, use the device's
persistent storage to persist the ID. The next time the user uses your
app on that device, get the client ID that you persisted. Bing
responses may or may not include this header. If the response includes
this header, capture the client ID and use it for all subsequent Bing
requests for the user on that device. If you include the
X-MSEdge-ClientID, you must not include cookies in the request.
:type client_id: str
:param client_ip: The IPv4 or IPv6 address of the client device. The
IP address is used to discover the user's location. Bing uses the
location information to determine safe search behavior. Although
optional, you are encouraged to always specify this header and the
X-Search-Location header. Do not obfuscate the address (for example,
by changing the last octet to 0). Obfuscating the address results in
the location not being anywhere near the device's actual location,
which may result in Bing serving erroneous results.
:type client_ip: str
:param location: A semicolon-delimited list of key/value pairs that
describe the client's geographical location. Bing uses the location
information to determine safe search behavior and to return relevant
local content. Specify the key/value pair as <key>:<value>. The
following are the keys that you use to specify the user's location.
lat (required): The latitude of the client's location, in degrees. The
latitude must be greater than or equal to -90.0 and less than or equal
to +90.0. Negative values indicate southern latitudes and positive
values indicate northern latitudes. long (required): The longitude of
the client's location, in degrees. The longitude must be greater than
or equal to -180.0 and less than or equal to +180.0. Negative values
indicate western longitudes and positive values indicate eastern
longitudes. re (required): The radius, in meters, which specifies the
horizontal accuracy of the coordinates. Pass the value returned by the
device's location service. Typical values might be 22m for GPS/Wi-Fi,
380m for cell tower triangulation, and 18,000m for reverse IP lookup.
ts (optional): The UTC UNIX timestamp of when the client was at the
location. (The UNIX timestamp is the number of seconds since January
1, 1970.) head (optional): The client's relative heading or direction
of travel. Specify the direction of travel as degrees from 0 through
360, counting clockwise relative to true north. Specify this key only
if the sp key is nonzero. sp (optional): The horizontal velocity
(speed), in meters per second, that the client device is traveling.
alt (optional): The altitude of the client device, in meters. are
(optional): The radius, in meters, that specifies the vertical
accuracy of the coordinates. Specify this key only if you specify the
alt key. Although many of the keys are optional, the more information
that you provide, the more accurate the location results are. Although
optional, you are encouraged to always specify the user's geographical
location. Providing the location is especially important if the
client's IP address does not accurately reflect the user's physical
location (for example, if the client uses VPN). For optimal results,
you should include this header and the X-MSEdge-ClientIP header, but
at a minimum, you should include this header.
:type location: str
:param aspect: Filter images by the following aspect ratios. All: Do
not filter by aspect.Specifying this value is the same as not
specifying the aspect parameter. Square: Return images with standard
aspect ratio. Wide: Return images with wide screen aspect ratio. Tall:
Return images with tall aspect ratio. Possible values include: 'All',
'Square', 'Wide', 'Tall'
:type aspect: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageAspect
:param color: Filter images by the following color options. ColorOnly:
Return color images. Monochrome: Return black and white images. Return
images with one of the following dominant colors: Black, Blue, Brown,
Gray, Green, Orange, Pink, Purple, Red, Teal, White, Yellow. Possible
values include: 'ColorOnly', 'Monochrome', 'Black', 'Blue', 'Brown',
'Gray', 'Green', 'Orange', 'Pink', 'Purple', 'Red', 'Teal', 'White',
'Yellow'
:type color: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageColor
:param country_code: A 2-character country code of the country where
the results come from. For a list of possible values, see [Market
Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes).
If you set this parameter, you must also specify the
[Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
header. Bing uses the first supported language it finds from the
languages list, and combine that language with the country code that
you specify to determine the market to return results for. If the
languages list does not include a supported language, Bing finds the
closest language and market that supports the request, or it may use
an aggregated or default market for the results instead of a specified
one. You should use this query parameter and the Accept-Language query
parameter only if you specify multiple languages; otherwise, you
should use the mkt and setLang query parameters. This parameter and
the
[mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#mkt)
query parameter are mutually exclusive—do not specify both.
:type country_code: str
:param count: The number of images to return in the response. The
actual number delivered may be less than requested. The default is 35.
The maximum value is 150. You use this parameter along with the offset
parameter to page results.For example, if your user interface displays
20 images per page, set count to 20 and offset to 0 to get the first
page of results.For each subsequent page, increment offset by 20 (for
example, 0, 20, 40). Use this parameter only with the Image Search
API.Do not specify this parameter when calling the Insights, Trending
Images, or Web Search APIs.
:type count: int
:param freshness: Filter images by the following discovery options.
Day: Return images discovered by Bing within the last 24 hours. Week:
Return images discovered by Bing within the last 7 days. Month: Return
images discovered by Bing within the last 30 days. Possible values
include: 'Day', 'Week', 'Month'
:type freshness: str or
~azure.cognitiveservices.search.customimagesearch.models.Freshness
:param height: Filter images that have the specified height, in
pixels. You may use this filter with the size filter to return small
images that have a height of 150 pixels.
:type height: int
:param id: An ID that uniquely identifies an image. Use this parameter
to ensure that the specified image is the first image in the list of
images that Bing returns. The
[Image](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#image)
object's imageId field contains the ID that you set this parameter to.
:type id: str
:param image_content: Filter images by the following content types.
Face: Return images that show only a person's face. Portrait: Return
images that show only a person's head and shoulders. Possible values
include: 'Face', 'Portrait'
:type image_content: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageContent
:param image_type: Filter images by the following image types.
AnimatedGif: Return only animated GIFs. Clipart: Return only clip art
images. Line: Return only line drawings. Photo: Return only
photographs(excluding line drawings, animated Gifs, and clip art).
Shopping: Return only images that contain items where Bing knows of a
merchant that is selling the items. This option is valid in the en -
US market only.Transparent: Return only images with a transparent
background. Possible values include: 'AnimatedGif', 'Clipart', 'Line',
'Photo', 'Shopping', 'Transparent'
:type image_type: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageType
:param license: Filter images by the following license types. All: Do
not filter by license type.Specifying this value is the same as not
specifying the license parameter. Any: Return images that are under
any license type. The response doesn't include images that do not
specify a license or the license is unknown. Public: Return images
where the creator has waived their exclusive rights, to the fullest
extent allowed by law. Share: Return images that may be shared with
others. Changing or editing the image might not be allowed. Also,
modifying, sharing, and using the image for commercial purposes might
not be allowed. Typically, this option returns the most images.
ShareCommercially: Return images that may be shared with others for
personal or commercial purposes. Changing or editing the image might
not be allowed. Modify: Return images that may be modified, shared,
and used. Changing or editing the image might not be allowed.
Modifying, sharing, and using the image for commercial purposes might
not be allowed. ModifyCommercially: Return images that may be
modified, shared, and used for personal or commercial purposes.
Typically, this option returns the fewest images. For more information
about these license types, see [Filter Images By License
Type](http://go.microsoft.com/fwlink/?LinkId=309768). Possible values
include: 'All', 'Any', 'Public', 'Share', 'ShareCommercially',
'Modify', 'ModifyCommercially'
:type license: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageLicense
:param market: The market where the results come from. Typically, mkt
is the country where the user is making the request from. However, it
could be a different country if the user is not located in a country
where Bing delivers results. The market must be in the form <language
code>-<country code>. For example, en-US. The string is case
insensitive. For a list of possible market values, see [Market
Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes).
NOTE: If known, you are encouraged to always specify the market.
Specifying the market helps Bing route the request and return an
appropriate and optimal response. If you specify a market that is not
listed in [Market
Codes](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#market-codes),
Bing uses a best fit market code based on an internal mapping that is
subject to change. This parameter and the
[cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#cc)
query parameter are mutually exclusive—do not specify both.
:type market: str
:param max_file_size: Filter images that are less than or equal to the
specified file size. The maximum file size that you may specify is
520,192 bytes. If you specify a larger value, the API uses 520,192. It
is possible that the response may include images that are slightly
larger than the specified maximum. You may specify this filter and
minFileSize to filter images within a range of file sizes.
:type max_file_size: long
:param max_height: Filter images that have a height that is less than
or equal to the specified height. Specify the height in pixels. You
may specify this filter and minHeight to filter images within a range
of heights. This filter and the height filter are mutually exclusive.
:type max_height: long
:param max_width: Filter images that have a width that is less than or
equal to the specified width. Specify the width in pixels. You may
specify this filter and maxWidth to filter images within a range of
widths. This filter and the width filter are mutually exclusive.
:type max_width: long
:param min_file_size: Filter images that are greater than or equal to
the specified file size. The maximum file size that you may specify is
520,192 bytes. If you specify a larger value, the API uses 520,192. It
is possible that the response may include images that are slightly
smaller than the specified minimum. You may specify this filter and
maxFileSize to filter images within a range of file sizes.
:type min_file_size: long
:param min_height: Filter images that have a height that is greater
than or equal to the specified height. Specify the height in pixels.
You may specify this filter and maxHeight to filter images within a
range of heights. This filter and the height filter are mutually
exclusive.
:type min_height: long
:param min_width: Filter images that have a width that is greater than
or equal to the specified width. Specify the width in pixels. You may
specify this filter and maxWidth to filter images within a range of
widths. This filter and the width filter are mutually exclusive.
:type min_width: long
:param offset: The zero-based offset that indicates the number of
images to skip before returning images. The default is 0. The offset
should be less than
([totalEstimatedMatches](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#totalestimatedmatches)
- count). Use this parameter along with the count parameter to page
results. For example, if your user interface displays 20 images per
page, set count to 20 and offset to 0 to get the first page of
results. For each subsequent page, increment offset by 20 (for
example, 0, 20, 40). It is possible for multiple pages to include some
overlap in results. To prevent duplicates, see
[nextOffset](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#nextoffset).
Use this parameter only with the Image API. Do not specify this
parameter when calling the Trending Images API or the Web Search API.
:type offset: long
:param safe_search: Filter images for adult content. The following are
the possible filter values. Off: May return images with adult content.
If the request is through the Image Search API, the response includes
thumbnail images that are clear (non-fuzzy). However, if the request
is through the Web Search API, the response includes thumbnail images
that are pixelated (fuzzy). Moderate: If the request is through the
Image Search API, the response doesn't include images with adult
content. If the request is through the Web Search API, the response
may include images with adult content (the thumbnail images are
pixelated (fuzzy)). Strict: Do not return images with adult content.
The default is Moderate. If the request comes from a market that
Bing's adult policy requires that safeSearch is set to Strict, Bing
ignores the safeSearch value and uses Strict. If you use the site:
query operator, there is the chance that the response may contain
adult content regardless of what the safeSearch query parameter is set
to. Use site: only if you are aware of the content on the site and
your scenario supports the possibility of adult content. Possible
values include: 'Off', 'Moderate', 'Strict'
:type safe_search: str or
~azure.cognitiveservices.search.customimagesearch.models.SafeSearch
:param size: Filter images by the following sizes. All: Do not filter
by size. Specifying this value is the same as not specifying the size
parameter. Small: Return images that are less than 200x200 pixels.
Medium: Return images that are greater than or equal to 200x200 pixels
but less than 500x500 pixels. Large: Return images that are 500x500
pixels or larger. Wallpaper: Return wallpaper images. You may use this
parameter along with the height or width parameters. For example, you
may use height and size to request small images that are 150 pixels
tall. Possible values include: 'All', 'Small', 'Medium', 'Large',
'Wallpaper'
:type size: str or
~azure.cognitiveservices.search.customimagesearch.models.ImageSize
:param set_lang: The language to use for user interface strings.
Specify the language using the ISO 639-1 2-letter language code. For
example, the language code for English is EN. The default is EN
(English). Although optional, you should always specify the language.
Typically, you set setLang to the same language specified by mkt
unless the user wants the user interface strings displayed in a
different language. This parameter and the
[Accept-Language](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#acceptlanguage)
header are mutually exclusive; do not specify both. A user interface
string is a string that's used as a label in a user interface. There
are few user interface strings in the JSON response objects. Also, any
links to Bing.com properties in the response objects apply the
specified language.
:type set_lang: str
:param width: Filter images that have the specified width, in pixels.
You may use this filter with the size filter to return small images
that have a width of 150 pixels.
:type width: int
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: Images or ClientRawResponse if raw=true
:rtype:
~azure.cognitiveservices.search.customimagesearch.models.Images or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`ErrorResponseException<azure.cognitiveservices.search.customimagesearch.models.ErrorResponseException>`
"""
# Construct URL
url = self.image_search.metadata['url']
# Construct parameters
query_parameters = {}
query_parameters['customConfig'] = self._serialize.query("custom_config", custom_config, 'long', minimum=0)
if aspect is not None:
query_parameters['aspect'] = self._serialize.query("aspect", aspect, 'str')
if color is not None:
query_parameters['color'] = self._serialize.query("color", color, 'str')
if country_code is not None:
query_parameters['cc'] = self._serialize.query("country_code", country_code, 'str')
if count is not None:
query_parameters['count'] = self._serialize.query("count", count, 'int')
if freshness is not None:
query_parameters['freshness'] = self._serialize.query("freshness", freshness, 'str')
if height is not None:
query_parameters['height'] = self._serialize.query("height", height, 'int')
if id is not None:
query_parameters['id'] = self._serialize.query("id", id, 'str')
if image_content is not None:
query_parameters['imageContent'] = self._serialize.query("image_content", image_content, 'str')
if image_type is not None:
query_parameters['imageType'] = self._serialize.query("image_type", image_type, 'str')
if license is not None:
query_parameters['license'] = self._serialize.query("license", license, 'str')
if market is not None:
query_parameters['mkt'] = self._serialize.query("market", market, 'str')
if max_file_size is not None:
query_parameters['maxFileSize'] = self._serialize.query("max_file_size", max_file_size, 'long')
if max_height is not None:
query_parameters['maxHeight'] = self._serialize.query("max_height", max_height, 'long')
if max_width is not None:
query_parameters['maxWidth'] = self._serialize.query("max_width", max_width, 'long')
if min_file_size is not None:
query_parameters['minFileSize'] = self._serialize.query("min_file_size", min_file_size, 'long')
if min_height is not None:
query_parameters['minHeight'] = self._serialize.query("min_height", min_height, 'long')
if min_width is not None:
query_parameters['minWidth'] = self._serialize.query("min_width", min_width, 'long')
if offset is not None:
query_parameters['offset'] = self._serialize.query("offset", offset, 'long')
query_parameters['q'] = self._serialize.query("query", query, 'str')
if safe_search is not None:
query_parameters['safeSearch'] = self._serialize.query("safe_search", safe_search, 'str')
if size is not None:
query_parameters['size'] = self._serialize.query("size", size, 'str')
if set_lang is not None:
query_parameters['setLang'] = self._serialize.query("set_lang", set_lang, 'str')
if width is not None:
query_parameters['width'] = self._serialize.query("width", width, 'int')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
header_parameters['X-BingApis-SDK'] = self._serialize.header("self.x_bing_apis_sdk", self.x_bing_apis_sdk, 'str')
if accept_language is not None:
header_parameters['Accept-Language'] = self._serialize.header("accept_language", accept_language, 'str')
if user_agent is not None:
header_parameters['User-Agent'] = self._serialize.header("user_agent", user_agent, 'str')
if client_id is not None:
header_parameters['X-MSEdge-ClientID'] = self._serialize.header("client_id", client_id, 'str')
if client_ip is not None:
header_parameters['X-MSEdge-ClientIP'] = self._serialize.header("client_ip", client_ip, 'str')
if location is not None:
header_parameters['X-Search-Location'] = self._serialize.header("location", location, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.ErrorResponseException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('Images', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
|
Attempts to extract available streams.
|
def streams(self, stream_types=None, sorting_excludes=None):
"""Attempts to extract available streams.
Returns a :class:`dict` containing the streams, where the key is
the name of the stream, most commonly the quality and the value
is a :class:`Stream` object.
The result can contain the synonyms **best** and **worst** which
points to the streams which are likely to be of highest and
lowest quality respectively.
If multiple streams with the same name are found, the order of
streams specified in *stream_types* will determine which stream
gets to keep the name while the rest will be renamed to
"<name>_<stream type>".
The synonyms can be fine tuned with the *sorting_excludes*
parameter. This can be either of these types:
- A list of filter expressions in the format
*[operator]<value>*. For example the filter ">480p" will
exclude streams ranked higher than "480p" from the list
used in the synonyms ranking. Valid operators are >, >=, <
and <=. If no operator is specified then equality will be
tested.
- A function that is passed to filter() with a list of
stream names as input.
:param stream_types: A list of stream types to return.
:param sorting_excludes: Specify which streams to exclude from
the best/worst synonyms.
"""
try:
ostreams = self._get_streams()
if isinstance(ostreams, dict):
ostreams = ostreams.items()
# Flatten the iterator to a list so we can reuse it.
if ostreams:
ostreams = list(ostreams)
except NoStreamsError:
return {}
except (IOError, OSError, ValueError) as err:
raise PluginError(err)
if not ostreams:
return {}
if stream_types is None:
stream_types = self.default_stream_types(ostreams)
# Add streams depending on stream type and priorities
sorted_streams = sorted(iterate_streams(ostreams),
key=partial(stream_type_priority,
stream_types))
streams = {}
for name, stream in sorted_streams:
stream_type = type(stream).shortname()
# Use * as wildcard to match other stream types
if "*" not in stream_types and stream_type not in stream_types:
continue
# drop _alt from any stream names
if name.endswith("_alt"):
name = name[:-len("_alt")]
existing = streams.get(name)
if existing:
existing_stream_type = type(existing).shortname()
if existing_stream_type != stream_type:
name = "{0}_{1}".format(name, stream_type)
if name in streams:
name = "{0}_alt".format(name)
num_alts = len(list(filter(lambda n: n.startswith(name), streams.keys())))
# We shouldn't need more than 2 alt streams
if num_alts >= 2:
continue
elif num_alts > 0:
name = "{0}{1}".format(name, num_alts + 1)
# Validate stream name and discard the stream if it's bad.
match = re.match("([A-z0-9_+]+)", name)
if match:
name = match.group(1)
else:
self.logger.debug("The stream '{0}' has been ignored "
"since it is badly named.", name)
continue
# Force lowercase name and replace space with underscore.
streams[name.lower()] = stream
# Create the best/worst synonmys
def stream_weight_only(s):
return (self.stream_weight(s)[0] or
(len(streams) == 1 and 1))
stream_names = filter(stream_weight_only, streams.keys())
sorted_streams = sorted(stream_names, key=stream_weight_only)
unfiltered_sorted_streams = sorted_streams
if isinstance(sorting_excludes, list):
for expr in sorting_excludes:
filter_func = stream_sorting_filter(expr, self.stream_weight)
sorted_streams = list(filter(filter_func, sorted_streams))
elif callable(sorting_excludes):
sorted_streams = list(filter(sorting_excludes, sorted_streams))
final_sorted_streams = OrderedDict()
for stream_name in sorted(streams, key=stream_weight_only):
final_sorted_streams[stream_name] = streams[stream_name]
if len(sorted_streams) > 0:
best = sorted_streams[-1]
worst = sorted_streams[0]
final_sorted_streams["worst"] = streams[worst]
final_sorted_streams["best"] = streams[best]
elif len(unfiltered_sorted_streams) > 0:
best = unfiltered_sorted_streams[-1]
worst = unfiltered_sorted_streams[0]
final_sorted_streams["worst-unfiltered"] = streams[worst]
final_sorted_streams["best-unfiltered"] = streams[best]
return final_sorted_streams
|
Store the cookies from http in the plugin cache until they expire. The cookies can be filtered by supplying a filter method. eg. lambda c: auth in c. name. If no expiry date is given in the cookie then the default_expires value will be used.
|
def save_cookies(self, cookie_filter=None, default_expires=60 * 60 * 24 * 7):
"""
Store the cookies from ``http`` in the plugin cache until they expire. The cookies can be filtered
by supplying a filter method. eg. ``lambda c: "auth" in c.name``. If no expiry date is given in the
cookie then the ``default_expires`` value will be used.
:param cookie_filter: a function to filter the cookies
:type cookie_filter: function
:param default_expires: time (in seconds) until cookies with no expiry will expire
:type default_expires: int
:return: list of the saved cookie names
"""
if not self.session or not self.cache:
raise RuntimeError("Cannot cache cookies in unbound plugin")
cookie_filter = cookie_filter or (lambda c: True)
saved = []
for cookie in filter(cookie_filter, self.session.http.cookies):
cookie_dict = {}
for attr in ("version", "name", "value", "port", "domain", "path", "secure", "expires", "discard",
"comment", "comment_url", "rfc2109"):
cookie_dict[attr] = getattr(cookie, attr, None)
cookie_dict["rest"] = getattr(cookie, "rest", getattr(cookie, "_rest", None))
expires = default_expires
if cookie_dict['expires']:
expires = int(cookie_dict['expires'] - time.time())
key = "__cookie:{0}:{1}:{2}:{3}".format(cookie.name,
cookie.domain,
cookie.port_specified and cookie.port or "80",
cookie.path_specified and cookie.path or "*")
self.cache.set(key, cookie_dict, expires)
saved.append(cookie.name)
if saved:
self.logger.debug("Saved cookies: {0}".format(", ".join(saved)))
return saved
|
Load any stored cookies for the plugin that have not expired.
|
def load_cookies(self):
"""
Load any stored cookies for the plugin that have not expired.
:return: list of the restored cookie names
"""
if not self.session or not self.cache:
raise RuntimeError("Cannot loaded cached cookies in unbound plugin")
restored = []
for key, value in self.cache.get_all().items():
if key.startswith("__cookie"):
cookie = requests.cookies.create_cookie(**value)
self.session.http.cookies.set_cookie(cookie)
restored.append(cookie.name)
if restored:
self.logger.debug("Restored cookies: {0}".format(", ".join(restored)))
return restored
|
Removes all of the saved cookies for this Plugin. To filter the cookies that are deleted specify the cookie_filter argument ( see: func: save_cookies ).
|
def clear_cookies(self, cookie_filter=None):
"""
Removes all of the saved cookies for this Plugin. To filter the cookies that are deleted
specify the ``cookie_filter`` argument (see :func:`save_cookies`).
:param cookie_filter: a function to filter the cookies
:type cookie_filter: function
:return: list of the removed cookie names
"""
if not self.session or not self.cache:
raise RuntimeError("Cannot loaded cached cookies in unbound plugin")
cookie_filter = cookie_filter or (lambda c: True)
removed = []
for key, value in sorted(self.cache.get_all().items(), key=operator.itemgetter(0), reverse=True):
if key.startswith("__cookie"):
cookie = requests.cookies.create_cookie(**value)
if cookie_filter(cookie):
del self.session.http.cookies[cookie.name]
self.cache.set(key, None, 0)
removed.append(key)
return removed
|
Return a shell - escaped version of the string * s *.
|
def shlex_quote(s):
"""Return a shell-escaped version of the string *s*.
Backported from Python 3.3 standard library module shlex.
"""
if is_py3: # use the latest version instead of backporting if it's available
return quote(s)
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
|
Returns the width of the string it would be when displayed.
|
def terminal_width(value):
"""Returns the width of the string it would be when displayed."""
if isinstance(value, bytes):
value = value.decode("utf8", "ignore")
return sum(map(get_width, map(ord, value)))
|
Drops Characters by unicode not by bytes.
|
def get_cut_prefix(value, max_len):
"""Drops Characters by unicode not by bytes."""
should_convert = isinstance(value, bytes)
if should_convert:
value = value.decode("utf8", "ignore")
for i in range(len(value)):
if terminal_width(value[i:]) <= max_len:
break
return value[i:].encode("utf8", "ignore") if should_convert else value[i:]
|
Clears out the previous line and prints a new one.
|
def print_inplace(msg):
"""Clears out the previous line and prints a new one."""
term_width = get_terminal_size().columns
spacing = term_width - terminal_width(msg)
# On windows we need one less space or we overflow the line for some reason.
if is_win32:
spacing -= 1
sys.stderr.write("\r{0}".format(msg))
sys.stderr.write(" " * max(0, spacing))
sys.stderr.flush()
|
Formats the file size into a human readable format.
|
def format_filesize(size):
"""Formats the file size into a human readable format."""
for suffix in ("bytes", "KB", "MB", "GB", "TB"):
if size < 1024.0:
if suffix in ("GB", "TB"):
return "{0:3.2f} {1}".format(size, suffix)
else:
return "{0:3.1f} {1}".format(size, suffix)
size /= 1024.0
|
Formats elapsed seconds into a human readable format.
|
def format_time(elapsed):
"""Formats elapsed seconds into a human readable format."""
hours = int(elapsed / (60 * 60))
minutes = int((elapsed % (60 * 60)) / 60)
seconds = int(elapsed % 60)
rval = ""
if hours:
rval += "{0}h".format(hours)
if elapsed > 60:
rval += "{0}m".format(minutes)
rval += "{0}s".format(seconds)
return rval
|
Creates a status line with appropriate size.
|
def create_status_line(**params):
"""Creates a status line with appropriate size."""
max_size = get_terminal_size().columns - 1
for fmt in PROGRESS_FORMATS:
status = fmt.format(**params)
if len(status) <= max_size:
break
return status
|
Progress an iterator and updates a pretty status line to the terminal.
|
def progress(iterator, prefix):
"""Progress an iterator and updates a pretty status line to the terminal.
The status line contains:
- Amount of data read from the iterator
- Time elapsed
- Average speed, based on the last few seconds.
"""
if terminal_width(prefix) > 25:
prefix = (".." + get_cut_prefix(prefix, 23))
speed_updated = start = time()
speed_written = written = 0
speed_history = deque(maxlen=5)
for data in iterator:
yield data
now = time()
elapsed = now - start
written += len(data)
speed_elapsed = now - speed_updated
if speed_elapsed >= 0.5:
speed_history.appendleft((
written - speed_written,
speed_updated,
))
speed_updated = now
speed_written = written
speed_history_written = sum(h[0] for h in speed_history)
speed_history_elapsed = now - speed_history[-1][1]
speed = speed_history_written / speed_history_elapsed
status = create_status_line(
prefix=prefix,
written=format_filesize(written),
elapsed=format_time(elapsed),
speed=format_filesize(speed)
)
print_inplace(status)
sys.stderr.write("\n")
sys.stderr.flush()
|
yield the segment number and when it will be available There are two cases for segment number generation static and dynamic.
|
def segment_numbers(self):
"""
yield the segment number and when it will be available
There are two cases for segment number generation, static and dynamic.
In the case of static stream, the segment number starts at the startNumber and counts
up to the number of segments that are represented by the periods duration.
In the case of dynamic streams, the segments should appear at the specified time
in the simplest case the segment number is based on the time since the availabilityStartTime
:return:
"""
log.debug("Generating segment numbers for {0} playlist (id={1})".format(self.root.type, self.parent.id))
if self.root.type == u"static":
available_iter = repeat(epoch_start)
duration = self.period.duration.seconds or self.root.mediaPresentationDuration.seconds
if duration:
number_iter = range(self.startNumber, int(duration / self.duration_seconds) + 1)
else:
number_iter = count(self.startNumber)
else:
now = datetime.datetime.now(utc)
if self.presentationTimeOffset:
since_start = (now - self.presentationTimeOffset) - self.root.availabilityStartTime
available_start_date = self.root.availabilityStartTime + self.presentationTimeOffset + since_start
available_start = available_start_date
else:
since_start = now - self.root.availabilityStartTime
available_start = now
# if there is no delay, use a delay of 3 seconds
suggested_delay = datetime.timedelta(seconds=(self.root.suggestedPresentationDelay.total_seconds()
if self.root.suggestedPresentationDelay
else 3))
# the number of the segment that is available at NOW - SUGGESTED_DELAY - BUFFER_TIME
number_iter = count(self.startNumber +
int((since_start - suggested_delay - self.root.minBufferTime).total_seconds() /
self.duration_seconds))
# the time the segment number is available at NOW
available_iter = count_dt(available_start,
step=datetime.timedelta(seconds=self.duration_seconds))
for number, available_at in izip(number_iter, available_iter):
yield number, available_at
|
Segments are yielded when they are available
|
def segments(self, **kwargs):
"""
Segments are yielded when they are available
Segments appear on a time line, for dynamic content they are only available at a certain time
and sometimes for a limited time. For static content they are all available at the same time.
:param kwargs: extra args to pass to the segment template
:return: yields Segments
"""
segmentBase = self.segmentBase or self.walk_back_get_attr("segmentBase")
segmentLists = self.segmentList or self.walk_back_get_attr("segmentList")
segmentTemplate = self.segmentTemplate or self.walk_back_get_attr("segmentTemplate")
if segmentTemplate:
for segment in segmentTemplate.segments(RepresentationID=self.id,
Bandwidth=int(self.bandwidth * 1000),
**kwargs):
if segment.init:
yield segment
else:
yield segment
elif segmentLists:
for segmentList in segmentLists:
for segment in segmentList.segments:
yield segment
else:
yield Segment(self.base_url, 0, True, True)
|
od. clear () - > None. Remove all items from od.
|
def clear(self):
'od.clear() -> None. Remove all items from od.'
try:
for node in self.__map.itervalues():
del node[:]
root = self.__root
root[:] = [root, root, None]
self.__map.clear()
except AttributeError:
pass
dict.clear(self)
|
od. pop ( k [ d ] ) - > v remove specified key and return the corresponding value. If key is not found d is returned if given otherwise KeyError is raised.
|
def pop(self, key, default=__marker):
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised.
'''
if key in self:
result = self[key]
del self[key]
return result
if default is self.__marker:
raise KeyError(key)
return default
|
OD. fromkeys ( S [ v ] ) - > New ordered dictionary with keys from S and values equal to v ( which defaults to None ).
|
def fromkeys(cls, iterable, value=None):
'''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
and values equal to v (which defaults to None).
'''
d = cls()
for key in iterable:
d[key] = value
return d
|
Locates unique identifier ( room_id ) for the room.
|
def _get_room_id(self):
"""
Locates unique identifier ("room_id") for the room.
Returns the room_id as a string, or None if no room_id was found
"""
match_dict = _url_re.match(self.url).groupdict()
if match_dict['room_id'] is not None:
return match_dict['room_id']
else:
res = self.session.http.get(self.url, headers=self._headers)
match = _room_id_re.search(res.text)
if not match:
title = self.url.rsplit('/', 1)[-1]
self.logger.debug(_room_id_lookup_failure_log.format(title, 'primary'))
match = _room_id_alt_re.search(res.text)
if not match:
self.logger.debug(_room_id_lookup_failure_log.format(title, 'secondary'))
return # Raise exception?
return match.group('room_id')
|
Shuts down the thread.
|
def close(self):
"""Shuts down the thread."""
if not self.closed:
log.debug("Closing worker thread")
self.closed = True
if self._wait:
self._wait.set()
|
Pauses the thread for a specified time.
|
def wait(self, time):
"""Pauses the thread for a specified time.
Returns False if interrupted by another thread and True if the
time runs out normally.
"""
self._wait = Event()
return not self._wait.wait(time)
|
Shuts down the thread.
|
def close(self):
"""Shuts down the thread."""
if not self.closed:
log.debug("Closing writer thread")
self.closed = True
self.reader.buffer.close()
self.executor.shutdown(wait=False)
if concurrent.futures.thread._threads_queues:
concurrent.futures.thread._threads_queues.clear()
|
Adds a segment to the download pool and write queue.
|
def put(self, segment):
"""Adds a segment to the download pool and write queue."""
if self.closed:
return
if segment is not None:
future = self.executor.submit(self.fetch, segment,
retries=self.retries)
else:
future = None
self.queue(self.futures, (segment, future))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.