Skip to content
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

[communication]-[sms]-Fixes mypy type errors. #37805

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import base64
import hmac
from urllib.parse import ParseResult, urlparse
from typing import Union
from typing import Union, Any
from azure.core.credentials import AzureKeyCredential
from azure.core.pipeline.policies import SansIOHTTPPolicy
from .utils import get_current_utc_time
Expand Down Expand Up @@ -56,7 +56,7 @@ def _compute_hmac(

return base64.b64encode(digest).decode("utf-8")

def _sign_request(self, request):
def _sign_request(self, request: Any):
verb = request.http_request.method.upper()

# Get the path and query from url, which looks like https://host/path/query
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def from_connection_string(cls, conn_str, # type: str
"""
endpoint, access_key = parse_connection_str(conn_str)

return cls(endpoint, access_key, **kwargs)
return cls(endpoint, AzureKeyCredential(access_key), **kwargs)

@distributed_trace
def send(self, from_, # type: str
Expand All @@ -88,7 +88,7 @@ def send(self, from_, # type: str
enable_delivery_report: bool = False,
tag: Optional[str] = None,
**kwargs: Any
): # type: (...) -> [SmsSendResult]
) -> List[SmsSendResult]:
"""Sends SMSs to phone numbers.

:param str from_: The sender of the SMS.
Expand Down Expand Up @@ -124,15 +124,17 @@ def send(self, from_, # type: str
sms_send_options=sms_send_options,
**kwargs)

return self._sms_service_client.sms.send(
response = self._sms_service_client.sms.send(
request,
cls=lambda pr, r, e: [
SmsSendResult(
to=item.to,
message_id=item.message_id,
http_status_code=item.http_status_code,
successful=item.successful,
error_message=item.error_message
) for item in r.value
],
**kwargs)
**kwargs
)

return [
SmsSendResult(
to=item.to,
message_id=item.message_id,
http_status_code=item.http_status_code,
successful=item.successful,
error_message=item.error_message
) for item in response.value
]
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ class SmsClient(object): # pylint: disable=client-accepts-api-version-keyword
:param Union[AsyncTokenCredential, AzureKeyCredential] credential:
The credential we use to authenticate against the service.
"""

def __init__(
self,
endpoint: str,
credential: Union[AsyncTokenCredential, AzureKeyCredential],
**kwargs: Any,
) -> None:
) -> None:
try:
if not endpoint.lower().startswith('http'):
endpoint = "https://" + endpoint
Expand Down Expand Up @@ -76,18 +77,18 @@ def from_connection_string(cls, conn_str: str, **kwargs: Any) -> 'SmsClient':
:caption: Creating the SmsClient from a connection string.
"""
endpoint, access_key = parse_connection_str(conn_str)
return cls(endpoint, access_key, **kwargs)
return cls(endpoint, AzureKeyCredential(access_key), **kwargs)

@distributed_trace_async
async def send(
self,
from_: str,
to: Union[str, List[str]],
message: str,
*,
enable_delivery_report: bool = False,
tag: Optional[str] = None,
**kwargs: Any
self,
from_: str,
to: Union[str, List[str]],
message: str,
*,
enable_delivery_report: bool = False,
tag: Optional[str] = None,
**kwargs: Any
) -> List[SmsSendResult]:
"""Sends SMSs to phone numbers.

Expand Down Expand Up @@ -123,18 +124,20 @@ async def send(
sms_send_options=sms_send_options,
**kwargs)

return await self._sms_service_client.sms.send(
response = await self._sms_service_client.sms.send(
request,
cls=lambda pr, r, e: [
SmsSendResult(
to=item.to,
message_id=item.message_id,
http_status_code=item.http_status_code,
successful=item.successful,
error_message=item.error_message
) for item in r.value
],
**kwargs)
**kwargs
)

return [
SmsSendResult(
to=item.to,
message_id=item.message_id,
http_status_code=item.http_status_code,
successful=item.successful,
error_message=item.error_message
) for item in response.value
]

async def __aenter__(self) -> 'SmsClient':
await self._sms_service_client.__aenter__()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,29 +24,35 @@

sys.path.append("..")

class SmsMultipleRecipientsSample(object):

class SmsMultipleRecipientsSample(object):
connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING")
phone_number = os.getenv("SMS_PHONE_NUMBER")

def send_sms_to_multiple_recipients(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')

sms_client = SmsClient.from_connection_string(self.connection_string)

# calling send() with sms values
sms_responses = sms_client.send(
from_=self.phone_number,
to=[self.phone_number, self.phone_number],
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property

for sms_response in sms_responses:
if (sms_response.successful):
if sms_response.successful:
print("Message with message id {} was successful sent to {}"
.format(sms_response.message_id, sms_response.to))
.format(sms_response.message_id, sms_response.to))
else:
print("Message failed to send to {} with the status code {} and error: {}"
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))


if __name__ == '__main__':
sample = SmsMultipleRecipientsSample()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ class SmsMultipleRecipientsSampleAsync(object):
phone_number = os.getenv("SMS_PHONE_NUMBER")

async def send_sms_to_multiple_recipients_async(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')

sms_client = SmsClient.from_connection_string(self.connection_string)

async with sms_client:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,16 @@

sys.path.append("..")

class SmsSingleRecipientSample(object):

class SmsSingleRecipientSample(object):
connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING")
phone_number = os.getenv("SMS_PHONE_NUMBER")

def send_sms_to_single_recipient(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')
# [START auth_from_connection_string]
sms_client = SmsClient.from_connection_string(self.connection_string)
# [END auth_from_connection_string]
Expand All @@ -39,16 +43,17 @@ def send_sms_to_single_recipient(self):
from_=self.phone_number,
to=self.phone_number,
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
sms_response = sms_responses[0]
if (sms_response.successful):

if sms_response.successful:
print("Message with message id {} was successful sent to {}"
.format(sms_response.message_id, sms_response.to))
.format(sms_response.message_id, sms_response.to))
else:
print("Message failed to send to {} with the status code {} and error: {}"
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))


if __name__ == '__main__':
sample = SmsSingleRecipientSample()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,16 @@

sys.path.append("..")

class SmsSingleRecipientSampleAsync(object):

class SmsSingleRecipientSampleAsync(object):
connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING")
phone_number = os.getenv("SMS_PHONE_NUMBER")

async def send_sms_to_single_recipient_async(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')
# [START auth_from_connection_string_async]
sms_client = SmsClient.from_connection_string(self.connection_string)
# [END auth_from_connection_string_async]
Expand All @@ -42,20 +46,21 @@ async def send_sms_to_single_recipient_async(self):
from_=self.phone_number,
to=self.phone_number,
message="Hello World via SMS",
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
enable_delivery_report=True, # optional property
tag="custom-tag") # optional property
sms_response = sms_responses[0]
if (sms_response.successful):

if sms_response.successful:
print("Message with message id {} was successful sent to {}"
.format(sms_response.message_id, sms_response.to))
.format(sms_response.message_id, sms_response.to))
else:
print("Message failed to send to {} with the status code {} and error: {}"
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
except Exception:
print(Exception)
pass


if __name__ == '__main__':
sample = SmsSingleRecipientSampleAsync()
asyncio.run(sample.send_sms_to_single_recipient_async())
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,16 @@

sys.path.append("..")

class SmsTokenCredentialAuthSample(object):

class SmsTokenCredentialAuthSample(object):
connection_string = os.getenv("COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING")
phone_number = os.getenv("SMS_PHONE_NUMBER")

def sms_token_credential_auth(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')
# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
# AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
endpoint, _ = parse_connection_str(self.connection_string)
Expand All @@ -43,13 +47,14 @@ def sms_token_credential_auth(self):
to=self.phone_number,
message="Hello World via SMS")
sms_response = sms_responses[0]
if (sms_response.successful):

if sms_response.successful:
print("Message with message id {} was successful sent to {}"
.format(sms_response.message_id, sms_response.to))
.format(sms_response.message_id, sms_response.to))
else:
print("Message failed to send to {} with the status code {} and error: {}"
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))
.format(sms_response.to, sms_response.http_status_code, sms_response.error_message))


if __name__ == '__main__':
sample = SmsTokenCredentialAuthSample()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ class SmsTokenCredentialAuthSampleAsync(object):
phone_number = os.getenv("SMS_PHONE_NUMBER")

async def sms_token_credential_auth_async(self):
if not self.connection_string or not self.phone_number:
raise ValueError(
'''Environment variables COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING and SMS_PHONE_NUMBER must be
set''')
# To use Azure Active Directory Authentication (DefaultAzureCredential) make sure to have
# AZURE_TENANT_ID, AZURE_CLIENT_ID and AZURE_CLIENT_SECRET as env variables.
endpoint, _ = parse_connection_str(self.connection_string)
Expand Down
Loading