sample python code for publishing notification hub

Reetesh 20 Reputation points
2024-02-17T07:38:35.52+00:00

Hi all, I have created notification hub, need sample python code to publish and subscribe


# Provided connection string

HUB_NAME = 
Azure Notification Hubs
Azure Notification Hubs
An Azure service that is used to send push notifications to all major platforms from the cloud or on-premises environments.
295 questions
0 comments No comments
{count} votes

Accepted answer
  1. RevelinoB 2,780 Reputation points
    2024-02-17T08:17:21.54+00:00

    Hi Reetesh,

    I noticed that the code snippet you've provided outlines a basic approach to sending a notification using Azure Notification Hubs. However, there are a couple of points that need correction or further clarification for it to work effectively. Primarily, the connection string and the way authorization is handled require adjustments. Here is a refined version of your code with some necessary changes and additional comments for clarity:

    import requests

    import urllib.parse import hmac import hashlib import base64 from datetime import datetime, timedelta # Your Notification Hub parameters HUB_NAME = "<Your_Hub_Name>" NAMESPACE = "<Your_Namespace>" SAS_KEY_NAME = "DefaultFullSharedAccessSignature" SAS_KEY_VALUE = "<Your_SAS_Key>" def generate_sas_token(uri, sas_key_name, sas_key_value): """Generate the SAS token for authentication.""" token_expiry = timedelta(hours=1) expiry = str(int((datetime.utcnow() + token_expiry).timestamp())) string_to_sign = (urllib.parse.quote_plus(uri) + '\n' + expiry).encode('utf-8') sas_key = sas_key_value.encode('utf-8') signed_hmac_sha256 = hmac.HMAC(sas_key, string_to_sign, hashlib.sha256) signature = urllib.parse.quote(base64.b64encode(signed_hmac_sha256.digest())) return f"SharedAccessSignature sr={urllib.parse.quote_plus(uri)}&sig={signature}&se={expiry}&skn={sas_key_name}" def send_notification(message): """Send a notification message.""" url = f"https://{NAMESPACE}.servicebus.windows.net/{HUB_NAME}/messages/?api-version=2015-01" uri = f"{NAMESPACE}.servicebus.windows.net/{HUB_NAME}" sas_token = generate_sas_token(uri, SAS_KEY_NAME, SAS_KEY_VALUE) headers = { "Authorization": sas_token, "Content-Type": "application/json", "ServiceBusNotification-Format": "gcm" # Use appropriate format (gcm for Android, apns for iOS, etc.) } payload = { "data": { "message": message } } response = requests.post(url, json=payload, headers=headers) if response.status_code == 201: print("Notification sent successfully.") else: print("Failed to send notification.") print(response.text)

    Example usage

    send_notification("Hello, Azure Notification Hubs!") Key Points:

    • SAS Token Generation: The generate_sas_token function creates a Shared Access Signature (SAS) token for authentication with the Azure Notification Hub. This is necessary for the authorization header.
    • Namespace and Hub Name: Ensure that NAMESPACE and HUB_NAME are correctly defined with your specific Azure Notification Hub details.
    • SAS Key Name and Value: These should be obtained from your Azure portal under the Notification Hub's "Access Policies".
    • Content Type and Notification Format: The Content-Type header is set to application/json. The ServiceBusNotification-Format header specifies the format of the notification (e.g., GCM for Google Cloud Messaging, APNS for Apple Push Notification Service). This should be chosen based on the target platform of your notifications.

    Before running this code, ensure you have the requests library installed. You can install it using pip if you haven't already: pip install requests

    This code does not cover subscribing to notifications, as that typically happens on the client-side (e.g., a mobile device or web application), where the device registers itself with Azure Notification Hubs to receive push notifications. I hope this helps, if you have any questions please let me know

    0 comments No comments

0 additional answers

Sort by: Most helpful