Skip to content

Commit 9d12dcf

Browse files
author
Rakshith Bhyravabhotla
authored
[EventGrid] Fix lint errors (#13640)
* Fix lint errors * comments
1 parent c799a11 commit 9d12dcf

File tree

13 files changed

+91
-83
lines changed

13 files changed

+91
-83
lines changed

eng/tox/allowed_pylint_failures.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
"azure-common",
3737
"azure-nspkg",
3838
"azure-servicemanagement-legacy",
39-
"azure-eventgrid",
4039
"azure-graphrbac",
4140
"azure-loganalytics",
4241
"azure-servicefabric",
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
1+
__path__ = __import__('pkgutil').extend_path(__path__, __name__)

sdk/eventgrid/azure-eventgrid/azure/eventgrid/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,11 @@
77
from ._publisher_client import EventGridPublisherClient
88
from ._consumer import EventGridConsumer
99
from ._helpers import generate_shared_access_signature
10-
from ._models import CloudEvent, CustomEvent, EventGridEvent, StorageBlobCreatedEventData
10+
from ._models import CloudEvent, CustomEvent, EventGridEvent
1111
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
1212
from ._version import VERSION
1313

1414
__all__ = ['EventGridPublisherClient', 'EventGridConsumer',
15-
'CloudEvent', 'CustomEvent', 'EventGridEvent', 'StorageBlobCreatedEventData',
16-
'generate_shared_access_signature', 'EventGridSharedAccessSignatureCredential']
15+
'CloudEvent', 'CustomEvent', 'EventGridEvent', 'generate_shared_access_signature',
16+
'EventGridSharedAccessSignatureCredential']
1717
__version__ = VERSION

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_consumer.py

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,21 @@
77
# --------------------------------------------------------------------------
88

99
from typing import TYPE_CHECKING
10-
import json
11-
import six
1210
import logging
13-
14-
from azure.core import PipelineClient
15-
from msrest import Deserializer, Serializer
11+
from ._models import CloudEvent, EventGridEvent
1612

1713
if TYPE_CHECKING:
1814
# pylint: disable=unused-import,ungrouped-imports
1915
from typing import Any
2016

2117
_LOGGER = logging.getLogger(__name__)
2218

23-
from ._models import CloudEvent, EventGridEvent
24-
2519
class EventGridConsumer(object):
2620
"""
27-
A consumer responsible for deserializing event handler messages, to allow for access to strongly typed Event objects.
21+
A consumer responsible for deserializing event handler messages, to allow for
22+
access to strongly typed Event objects.
2823
"""
29-
def decode_cloud_event(self, cloud_event, **kwargs):
24+
def decode_cloud_event(self, cloud_event, **kwargs): # pylint: disable=no-self-use
3025
# type: (Union[str, dict, bytes], Any) -> CloudEvent
3126
"""Single event following CloudEvent schema will be parsed and returned as Deserialized Event.
3227
:param cloud_event: The event to be deserialized.
@@ -37,17 +32,19 @@ def decode_cloud_event(self, cloud_event, **kwargs):
3732
"""
3833
encode = kwargs.pop('encoding', 'utf-8')
3934
try:
40-
cloud_event = CloudEvent._from_json(cloud_event, encode)
41-
deserialized_event = CloudEvent._from_generated(cloud_event)
42-
CloudEvent._deserialize_data(deserialized_event, deserialized_event.type)
43-
return deserialized_event
35+
cloud_event = CloudEvent._from_json(cloud_event, encode) # pylint: disable=protected-access
36+
deserialized_event = CloudEvent._from_generated(cloud_event) # pylint: disable=protected-access
37+
CloudEvent._deserialize_data(deserialized_event, deserialized_event.type) # pylint: disable=protected-access
38+
return deserialized_event
4439
except Exception as err:
45-
_LOGGER.error('Error: cannot deserialize event. Event does not have a valid format. Event must be a string, dict, or bytes following the CloudEvent schema.')
46-
_LOGGER.error('Your event: {}'.format(cloud_event))
40+
_LOGGER.error('Error: cannot deserialize event. Event does not have a valid format. \
41+
Event must be a string, dict, or bytes following the CloudEvent schema.')
42+
_LOGGER.error('Your event: %s', cloud_event)
4743
_LOGGER.error(err)
48-
raise ValueError('Error: cannot deserialize event. Event does not have a valid format. Event must be a string, dict, or bytes following the CloudEvent schema.')
44+
raise ValueError('Error: cannot deserialize event. Event does not have a valid format. \
45+
Event must be a string, dict, or bytes following the CloudEvent schema.')
4946

50-
def decode_eventgrid_event(self, eventgrid_event, **kwargs):
47+
def decode_eventgrid_event(self, eventgrid_event, **kwargs): # pylint: disable=no-self-use
5148
# type: (Union[str, dict, bytes], Any) -> EventGridEvent
5249
"""Single event following EventGridEvent schema will be parsed and returned as Deserialized Event.
5350
:param eventgrid_event: The event to be deserialized.
@@ -58,12 +55,14 @@ def decode_eventgrid_event(self, eventgrid_event, **kwargs):
5855
"""
5956
encode = kwargs.pop('encoding', 'utf-8')
6057
try:
61-
eventgrid_event = EventGridEvent._from_json(eventgrid_event, encode)
58+
eventgrid_event = EventGridEvent._from_json(eventgrid_event, encode) # pylint: disable=protected-access
6259
deserialized_event = EventGridEvent.deserialize(eventgrid_event)
63-
EventGridEvent._deserialize_data(deserialized_event, deserialized_event.event_type)
60+
EventGridEvent._deserialize_data(deserialized_event, deserialized_event.event_type) # pylint: disable=protected-access
6461
return deserialized_event
6562
except Exception as err:
66-
_LOGGER.error('Error: cannot deserialize event. Event does not have a valid format. Event must be a string, dict, or bytes following the CloudEvent schema.')
67-
_LOGGER.error('Your event: {}'.format(eventgrid_event))
63+
_LOGGER.error('Error: cannot deserialize event. Event does not have a valid format. \
64+
Event must be a string, dict, or bytes following the CloudEvent schema.')
65+
_LOGGER.error('Your event: %s', eventgrid_event)
6866
_LOGGER.error(err)
69-
raise ValueError('Error: cannot deserialize event. Event does not have a valid format. Event must be a string, dict, or bytes following the CloudEvent schema.')
67+
raise ValueError('Error: cannot deserialize event. Event does not have a valid format. \
68+
Event must be a string, dict, or bytes following the CloudEvent schema.')

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_event_mappings.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
"Microsoft.EventGrid.SubscriptionValidationEvent": models.SubscriptionValidationEventData,
2020
"Microsoft.EventGrid.SubscriptionDeletedEvent": models.SubscriptionDeletedEventData,
2121
"Microsoft.EventHub.CaptureFileCreated": models.EventHubCaptureFileCreatedEventData,
22-
"Microsoft.MachineLearningServices.DatasetDriftDetected": models.MachineLearningServicesDatasetDriftDetectedEventData,
22+
"Microsoft.MachineLearningServices.DatasetDriftDetected":
23+
models.MachineLearningServicesDatasetDriftDetectedEventData,
2324
"Microsoft.MachineLearningServices.ModelDeployed": models.MachineLearningServicesModelDeployedEventData,
2425
"Microsoft.MachineLearningServices.ModelRegistered": models.MachineLearningServicesModelRegisteredEventData,
2526
"Microsoft.MachineLearningServices.RunCompleted": models.MachineLearningServicesRunCompletedEventData,
@@ -47,7 +48,8 @@
4748
"Microsoft.Media.LiveEventEncoderDisconnected": models.MediaLiveEventEncoderDisconnectedEventData,
4849
"Microsoft.Media.LiveEventIncomingStreamReceived": models.MediaLiveEventIncomingStreamReceivedEventData,
4950
"Microsoft.Media.LiveEventIncomingStreamsOutOfSync": models.MediaLiveEventIncomingStreamsOutOfSyncEventData,
50-
"Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync": models.MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
51+
"Microsoft.Media.LiveEventIncomingVideoStreamsOutOfSync":
52+
models.MediaLiveEventIncomingVideoStreamsOutOfSyncEventData,
5153
"Microsoft.Media.LiveEventIncomingDataChunkDropped": models.MediaLiveEventIncomingDataChunkDroppedEventData,
5254
"Microsoft.Media.LiveEventIngestHeartbeat": models.MediaLiveEventIngestHeartbeatEventData,
5355
"Microsoft.Media.LiveEventTrackDiscontinuityDetected": models.MediaLiveEventTrackDiscontinuityDetectedEventData,
@@ -60,8 +62,10 @@
6062
"Microsoft.Resources.ResourceActionSuccess": models.ResourceActionSuccessData,
6163
"Microsoft.Resources.ResourceActionFailure": models.ResourceActionFailureData,
6264
"Microsoft.Resources.ResourceActionCancel": models.ResourceActionCancelData,
63-
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners": models.ServiceBusActiveMessagesAvailableWithNoListenersEventData,
64-
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener": models.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
65+
"Microsoft.ServiceBus.ActiveMessagesAvailableWithNoListeners":
66+
models.ServiceBusActiveMessagesAvailableWithNoListenersEventData,
67+
"Microsoft.ServiceBus.DeadletterMessagesAvailableWithNoListener":
68+
models.ServiceBusDeadletterMessagesAvailableWithNoListenersEventData,
6569
"Microsoft.Storage.BlobCreated": models.StorageBlobCreatedEventData,
6670
"Microsoft.Storage.BlobDeleted": models.StorageBlobDeletedEventData,
6771
"Microsoft.Storage.BlobRenamed": models.StorageBlobRenamedEventData,
@@ -82,4 +86,4 @@
8286
"Microsoft.Web.SlotSwapWithPreviewStarted": models.WebSlotSwapWithPreviewStartedEventData,
8387
"Microsoft.Web.SlotSwapWithPreviewCancelled": models.WebSlotSwapWithPreviewCancelledEventData,
8488
"Microsoft.Web.AppServicePlanUpdated": models.WebAppServicePlanUpdatedEventData,
85-
}
89+
}

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_helpers.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,20 @@
1+
# --------------------------------------------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License. See License.txt in the project root for license information.
4+
# --------------------------------------------------------------------------------------------
15
import hashlib
26
import hmac
37
import base64
48
try:
59
from urllib.parse import quote
610
except ImportError:
711
from urllib2 import quote # type: ignore
8-
import datetime
912

1013
from azure.core.pipeline.policies import AzureKeyCredentialPolicy
1114
from azure.core.credentials import AzureKeyCredential
1215
from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential
1316
from ._signature_credential_policy import EventGridSharedAccessSignatureCredentialPolicy
1417
from . import _constants as constants
15-
from ._event_mappings import _event_mappings
1618

1719
def generate_shared_access_signature(topic_hostname, shared_access_key, expiration_date_utc, **kwargs):
1820
# type: (str, str, datetime.Datetime, Any) -> str
@@ -21,13 +23,17 @@ def generate_shared_access_signature(topic_hostname, shared_access_key, expirati
2123
Similar to <YOUR-TOPIC-NAME>.<YOUR-REGION-NAME>-1.eventgrid.azure.net
2224
:param str shared_access_key: The shared access key to be used for generating the token
2325
:param datetime.datetime expiration_date_utc: The expiration datetime in UTC for the signature.
24-
:param str api_version: The API Version to include in the signature. If not provided, the default API version will be used.
26+
:param str api_version: The API Version to include in the signature.
27+
If not provided, the default API version will be used.
2528
:rtype: str
2629
"""
2730

2831
full_topic_hostname = _get_full_topic_hostname(topic_hostname)
2932

30-
full_topic_hostname = "{}?apiVersion={}".format(full_topic_hostname, kwargs.get('api_version', None) or constants.DEFAULT_API_VERSION)
33+
full_topic_hostname = "{}?apiVersion={}".format(
34+
full_topic_hostname,
35+
kwargs.get('api_version', None) or constants.DEFAULT_API_VERSION
36+
)
3137
encoded_resource = quote(full_topic_hostname, safe=constants.SAFE_ENCODE)
3238
encoded_expiration_utc = quote(str(expiration_date_utc), safe=constants.SAFE_ENCODE)
3339

@@ -43,7 +49,7 @@ def _get_topic_hostname_only_fqdn(topic_hostname):
4349
topic_hostname = topic_hostname.replace("https://", "")
4450
if topic_hostname.endswith("/api/events"):
4551
topic_hostname = topic_hostname.replace("/api/events", "")
46-
52+
4753
return topic_hostname
4854

4955
def _get_full_topic_hostname(topic_hostname):
@@ -53,7 +59,7 @@ def _get_full_topic_hostname(topic_hostname):
5359
topic_hostname = "https://{}".format(topic_hostname)
5460
if not topic_hostname.endswith("/api/events"):
5561
topic_hostname = "{}/api/events".format(topic_hostname)
56-
62+
5763
return topic_hostname
5864

5965
def _generate_hmac(key, message):
@@ -69,7 +75,10 @@ def _get_authentication_policy(credential):
6975
if isinstance(credential, AzureKeyCredential):
7076
authentication_policy = AzureKeyCredentialPolicy(credential=credential, name=constants.EVENTGRID_KEY_HEADER)
7177
if isinstance(credential, EventGridSharedAccessSignatureCredential):
72-
authentication_policy = EventGridSharedAccessSignatureCredentialPolicy(credential=credential, name=constants.EVENTGRID_TOKEN_HEADER)
78+
authentication_policy = EventGridSharedAccessSignatureCredentialPolicy(
79+
credential=credential,
80+
name=constants.EVENTGRID_TOKEN_HEADER
81+
)
7382
return authentication_policy
7483

7584
def _is_cloud_event(event):

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_models.py

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,12 @@
33
# Licensed under the MIT License. See License.txt in the project root for license information.
44
# --------------------------------------------------------------------------------------------
55
# pylint:disable=protected-access
6-
from typing import Optional
7-
from msrest.serialization import UTC
86
import datetime as dt
97
import uuid
108
import json
119
import six
12-
from ._generated import models
13-
from ._generated.models import StorageBlobCreatedEventData, \
14-
EventGridEvent as InternalEventGridEvent, \
15-
CloudEvent as InternalCloudEvent
10+
from msrest.serialization import UTC
11+
from ._generated.models import EventGridEvent as InternalEventGridEvent, CloudEvent as InternalCloudEvent
1612
from ._shared.mixins import DictMixin
1713
from ._event_mappings import _event_mappings
1814

@@ -55,8 +51,8 @@ class CloudEvent(EventMixin): #pylint:disable=too-many-instance-attributes
5551
5652
All required parameters must be populated in order to send to Azure.
5753
58-
:param source: Required. Identifies the context in which an event happened. The combination of id and source must be
59-
unique for each distinct event. If publishing to a domain topic, source must be the domain name.
54+
:param source: Required. Identifies the context in which an event happened. The combination of id and source must
55+
be unique for each distinct event. If publishing to a domain topic, source must be the domain name.
6056
:type source: str
6157
:param data: Event data specific to the event type.
6258
:type data: object
@@ -75,7 +71,7 @@ class CloudEvent(EventMixin): #pylint:disable=too-many-instance-attributes
7571
unique for each distinct event.
7672
:type id: Optional[str]
7773
"""
78-
def __init__(self, source, type, **kwargs):
74+
def __init__(self, source, type, **kwargs): # pylint: disable=redefined-builtin
7975
# type: (str, str, Any) -> None
8076
self.source = source
8177
self.type = type
@@ -87,13 +83,13 @@ def __init__(self, source, type, **kwargs):
8783
self.dataschema = kwargs.pop("dataschema", None)
8884
self.subject = kwargs.pop("subject", None)
8985
self.extensions = {}
90-
self.extensions.update({k:v for k, v in kwargs.pop('extensions', {}).items()})
86+
self.extensions.update(dict(kwargs.pop('extensions', {})))
9187

9288
@classmethod
9389
def _from_generated(cls, cloud_event, **kwargs):
9490
generated = InternalCloudEvent.deserialize(cloud_event)
9591
if generated.additional_properties:
96-
extensions = {k:v for k, v in generated.additional_properties.items()}
92+
extensions = dict(generated.additional_properties)
9793
kwargs.setdefault('extensions', extensions)
9894
return cls(
9995
id=generated.id,
@@ -154,7 +150,8 @@ class EventGridEvent(InternalEventGridEvent, EventMixin):
154150
:param id: Optional. An identifier for the event. The combination of id and source must be
155151
unique for each distinct event.
156152
:type id: Optional[str]
157-
:param event_time: Optional.The time (in UTC) of the event. If not provided, it will be the time (in UTC) the event was generated.
153+
:param event_time: Optional.The time (in UTC) of the event. If not provided,
154+
it will be the time (in UTC) the event was generated.
158155
:type event_time: Optional[~datetime.datetime]
159156
"""
160157

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_publisher_client.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
# license information.
66
# --------------------------------------------------------------------------
77

8-
from typing import TYPE_CHECKING, Sequence
9-
import json
8+
from typing import TYPE_CHECKING
109

11-
from azure.core import PipelineClient
12-
from msrest import Deserializer, Serializer
10+
from ._models import CloudEvent, EventGridEvent, CustomEvent
11+
from ._helpers import _get_topic_hostname_only_fqdn, _get_authentication_policy, _is_cloud_event
12+
from ._generated._event_grid_publisher_client import EventGridPublisherClient as EventGridPublisherClientImpl
1313

1414
if TYPE_CHECKING:
1515
# pylint: disable=unused-import,ungrouped-imports
@@ -25,18 +25,14 @@
2525
List[Dict]
2626
]
2727

28-
from ._models import CloudEvent, EventGridEvent, CustomEvent
29-
from ._helpers import _get_topic_hostname_only_fqdn, _get_authentication_policy, _is_cloud_event
30-
from ._generated._event_grid_publisher_client import EventGridPublisherClient as EventGridPublisherClientImpl
31-
from . import _constants as constants
32-
3328

3429
class EventGridPublisherClient(object):
3530
"""EventGrid Python Publisher Client.
3631
3732
:param str topic_hostname: The topic endpoint to send the events to.
38-
:param credential: The credential object used for authentication which implements SAS key authentication or SAS token authentication.
39-
:type credential: Union[~azure.core.credentials.AzureKeyCredential, azure.eventgrid.EventGridSharedAccessSignatureCredential]
33+
:param credential: The credential object used for authentication which
34+
implements SAS key authentication or SAS token authentication.
35+
:type credential: ~azure.core.credentials.AzureKeyCredential or EventGridSharedAccessSignatureCredential
4036
"""
4137

4238
def __init__(self, topic_hostname, credential, **kwargs):
@@ -54,7 +50,8 @@ def send(self, events, **kwargs):
5450
:param events: A list or an instance of CloudEvent/EventGridEvent/CustomEvent to be sent.
5551
:type events: SendType
5652
:keyword str content_type: The type of content to be used to send the events.
57-
Has default value "application/json; charset=utf-8" for EventGridEvents, with "cloudevents-batch+json" for CloudEvents
53+
Has default value "application/json; charset=utf-8" for EventGridEvents,
54+
with "cloudevents-batch+json" for CloudEvents
5855
:rtype: None
5956
:raises: :class:`ValueError`, when events do not follow specified SendType.
6057
"""
@@ -63,7 +60,7 @@ def send(self, events, **kwargs):
6360

6461
if all(isinstance(e, CloudEvent) for e in events) or all(_is_cloud_event(e) for e in events):
6562
try:
66-
events = [e._to_generated(**kwargs) for e in events]
63+
events = [e._to_generated(**kwargs) for e in events] # pylint: disable=protected-access
6764
except AttributeError:
6865
pass # means it's a dictionary
6966
kwargs.setdefault("content_type", "application/cloudevents-batch+json; charset=utf-8")

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_shared/mixins.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -37,22 +37,22 @@ def __ne__(self, other):
3737
def __str__(self):
3838
return str({k: v for k, v in self.__dict__.items() if not k.startswith('_')})
3939

40-
def has_key(self, k, **kwargs):
40+
def has_key(self, k):
4141
return k in self.__dict__
4242

4343
def update(self, *args, **kwargs):
4444
return self.__dict__.update(*args, **kwargs)
4545

46-
def keys(self, **kwargs):
46+
def keys(self):
4747
return [k for k in self.__dict__ if not k.startswith('_')]
4848

49-
def values(self, **kwargs):
49+
def values(self):
5050
return [v for k, v in self.__dict__.items() if not k.startswith('_')]
5151

52-
def items(self, **kwargs):
52+
def items(self):
5353
return [(k, v) for k, v in self.__dict__.items() if not k.startswith('_')]
5454

55-
def get(self, key, default=None, **kwargs):
55+
def get(self, key, default=None):
5656
if key in self.__dict__:
5757
return self.__dict__[key]
5858
return default

sdk/eventgrid/azure-eventgrid/azure/eventgrid/_shared_access_signature_credential.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def signature(self):
2222
:rtype: str
2323
"""
2424
return self._signature
25-
25+
2626
def update(self, signature):
2727
# type: (str) -> None
2828
"""

0 commit comments

Comments
 (0)