-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Mypy Compatibilty for EventGrid #14344
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1 @@ | ||
| __path__ = __import__('pkgutil').extend_path(__path__, __name__) | ||
| __path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,13 +6,13 @@ | |
| # Changes may cause incorrect behavior and will be lost if the code is regenerated. | ||
| # -------------------------------------------------------------------------- | ||
|
|
||
| from typing import TYPE_CHECKING | ||
| from typing import cast, TYPE_CHECKING | ||
| import logging | ||
| from ._models import CloudEvent, EventGridEvent | ||
|
|
||
| if TYPE_CHECKING: | ||
| # pylint: disable=unused-import,ungrouped-imports | ||
| from typing import Any | ||
| from typing import Any, Union | ||
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
|
|
@@ -35,7 +35,7 @@ def decode_cloud_event(self, cloud_event, **kwargs): # pylint: disable=no-self-u | |
| cloud_event = CloudEvent._from_json(cloud_event, encode) # pylint: disable=protected-access | ||
| deserialized_event = CloudEvent._from_generated(cloud_event) # pylint: disable=protected-access | ||
| CloudEvent._deserialize_data(deserialized_event, deserialized_event.type) # pylint: disable=protected-access | ||
| return deserialized_event | ||
| return cast(CloudEvent, deserialized_event) | ||
| except Exception as err: | ||
| _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.') | ||
|
|
@@ -58,7 +58,7 @@ def decode_eventgrid_event(self, eventgrid_event, **kwargs): # pylint: disable=n | |
| eventgrid_event = EventGridEvent._from_json(eventgrid_event, encode) # pylint: disable=protected-access | ||
| deserialized_event = EventGridEvent.deserialize(eventgrid_event) | ||
| EventGridEvent._deserialize_data(deserialized_event, deserialized_event.event_type) # pylint: disable=protected-access | ||
| return deserialized_event | ||
| return cast(EventGridEvent, deserialized_event) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same question
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this is necessary unlike above - we get because the msrest's deserialize method on line 59 isn't typed
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Then let's fix msrest too :) But ok here, since we should not wait for msrest fix |
||
| except Exception as err: | ||
| _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.') | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ | |
| import hashlib | ||
| import hmac | ||
| import base64 | ||
| from typing import TYPE_CHECKING, Any | ||
| try: | ||
| from urllib.parse import quote | ||
| except ImportError: | ||
|
|
@@ -16,8 +17,11 @@ | |
| from ._signature_credential_policy import EventGridSharedAccessSignatureCredentialPolicy | ||
| from . import _constants as constants | ||
|
|
||
| if TYPE_CHECKING: | ||
| from datetime import datetime | ||
|
|
||
| def generate_shared_access_signature(topic_hostname, shared_access_key, expiration_date_utc, **kwargs): | ||
| # type: (str, str, datetime.Datetime, Any) -> str | ||
| # type: (str, str, datetime, Any) -> str | ||
| """ Helper method to generate shared access signature given hostname, key, and expiration date. | ||
| :param str topic_hostname: The topic endpoint to send the events to. | ||
| Similar to <YOUR-TOPIC-NAME>.<YOUR-REGION-NAME>-1.eventgrid.azure.net | ||
|
|
@@ -82,7 +86,7 @@ def _get_authentication_policy(credential): | |
| return authentication_policy | ||
|
|
||
| def _is_cloud_event(event): | ||
| # type: dict -> bool | ||
| # type: (dict) -> bool | ||
|
||
| required = ('id', 'source', 'specversion', 'type') | ||
| try: | ||
| return all([_ in event for _ in required]) and event['specversion'] == "1.0" | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,7 +5,7 @@ | |
| # license information. | ||
| # -------------------------------------------------------------------------- | ||
|
|
||
| from typing import TYPE_CHECKING | ||
| from typing import TYPE_CHECKING, cast, Dict, List, Any, Union | ||
|
|
||
| from azure.core.tracing.decorator import distributed_trace | ||
| from azure.core.pipeline.policies import ( | ||
|
|
@@ -27,10 +27,12 @@ | |
| from ._generated._event_grid_publisher_client import EventGridPublisherClient as EventGridPublisherClientImpl | ||
| from ._policies import CloudEventDistributedTracingPolicy | ||
| from ._version import VERSION | ||
| from ._generated.models import CloudEvent as InternalCloudEvent, EventGridEvent as InternalEventGridEvent | ||
|
|
||
| if TYPE_CHECKING: | ||
| # pylint: disable=unused-import,ungrouped-imports | ||
| from typing import Any, Union, Dict, List | ||
| from azure.core.credentials import AzureKeyCredential | ||
| from ._shared_access_signature_credential import EventGridSharedAccessSignatureCredential | ||
| SendType = Union[ | ||
| CloudEvent, | ||
| EventGridEvent, | ||
|
|
@@ -42,6 +44,13 @@ | |
| List[Dict] | ||
| ] | ||
|
|
||
| ListEventType = Union[ | ||
| List[CloudEvent], | ||
| List[EventGridEvent], | ||
| List[CustomEvent], | ||
| List[Dict] | ||
| ] | ||
|
|
||
|
|
||
| class EventGridPublisherClient(object): | ||
| """EventGrid Python Publisher Client. | ||
|
|
@@ -79,7 +88,7 @@ def _policies(credential, **kwargs): | |
| CustomHookPolicy(**kwargs), | ||
| NetworkTraceLoggingPolicy(**kwargs), | ||
| DistributedTracingPolicy(**kwargs), | ||
| CloudEventDistributedTracingPolicy(**kwargs), | ||
| CloudEventDistributedTracingPolicy(), | ||
| HttpLoggingPolicy(**kwargs) | ||
| ] | ||
| return policies | ||
|
|
@@ -98,20 +107,24 @@ def send(self, events, **kwargs): | |
| :raises: :class:`ValueError`, when events do not follow specified SendType. | ||
| """ | ||
| if not isinstance(events, list): | ||
| events = [events] | ||
| events = cast(ListEventType, [events]) | ||
|
|
||
| if all(isinstance(e, CloudEvent) for e in events) or all(_is_cloud_event(e) for e in events): | ||
| if all(isinstance(e, CloudEvent) for e in events) or all(_is_cloud_event(cast(Dict, e)) for e in events): | ||
|
||
| try: | ||
| events = [e._to_generated(**kwargs) for e in events] # pylint: disable=protected-access | ||
| events = [cast(CloudEvent, e)._to_generated(**kwargs) for e in events] # pylint: disable=protected-access | ||
| except AttributeError: | ||
| pass # means it's a dictionary | ||
| kwargs.setdefault("content_type", "application/cloudevents-batch+json; charset=utf-8") | ||
| self._client.publish_cloud_event_events(self._topic_hostname, events, **kwargs) | ||
| self._client.publish_cloud_event_events( | ||
| self._topic_hostname, | ||
| cast(List[InternalCloudEvent], events), | ||
| **kwargs | ||
| ) | ||
| elif all(isinstance(e, EventGridEvent) for e in events) or all(isinstance(e, dict) for e in events): | ||
| kwargs.setdefault("content_type", "application/json; charset=utf-8") | ||
| self._client.publish_events(self._topic_hostname, events, **kwargs) | ||
| self._client.publish_events(self._topic_hostname, cast(List[InternalEventGridEvent], events), **kwargs) | ||
| elif all(isinstance(e, CustomEvent) for e in events): | ||
| serialized_events = [dict(e) for e in events] | ||
| self._client.publish_custom_event_events(self._topic_hostname, serialized_events, **kwargs) | ||
| serialized_events = [dict(e) for e in events] # type: ignore | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why? What's the error?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| self._client.publish_custom_event_events(self._topic_hostname, cast(List, serialized_events), **kwargs) | ||
| else: | ||
| raise ValueError("Event schema is not correct.") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| [mypy] | ||
| python_version = 3.7 | ||
| warn_return_any = True | ||
| warn_unused_configs = True | ||
| ignore_missing_imports = True | ||
|
|
||
| # Per-module options: | ||
|
|
||
| [mypy-azure.eventgrid._generated.*] | ||
| ignore_errors = True | ||
|
|
||
| [mypy-azure.core.*] | ||
| ignore_errors = True |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What was the error that triggered the need for this cast? I would expect the return type of CloudEvent._from_generated to be CloudEvent , and then this cast unecessary
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This was unnecessary - removed it