aioapns

repository·master·Indexed 41 days ago

https://github.com/fatal1ty/aioapns

An efficient, asynchronous Apple Push Notification Service (APNs) client library for Python, built on asyncio and HTTP2. It supports both certificate-based and token-based (.p8 key) authentication, connection pooling, and sandbox environment switching.

Tokens
1.9K
Snippets
4
Records
5
Agent score
1%

What's inside aioapns

  1. Send push notifications with aioapns

    master

    To send notifications, you must first initialize an APNs client using either a certificate or a token-based approach. Then, create a NotificationRequest object containing the device_token and the notification message payload. Finally, call send_notification(request) on your client instance.

    Supported configuration options for APNs include:

    • client_cert: Path to the certificate file (for certificate-based auth).
    • key: The loaded key (for token-based auth).
    • key_id: Your Apple API Key ID.
    • team_id: Your Apple Team ID.
    • topic: Your app's Bundle ID.
    • use_sandbox: Boolean to switch between production and development APNs servers.
    import asyncio
    from uuid import uuid4
    from aioapns import APNs, NotificationRequest, PushType
    
    
    async def run():
        # Example using Certificate-based authentication
        apns_cert_client = APNs(
            client_cert='/path/to/apns-cert.pem',
            use_sandbox=False,
        )
    
        # Example using Token-based authentication (p8 key)
        # Note: 'read' is a placeholder for your logic to load the key file
        with open('/path/to/apns-key.p8', 'rb') as f:
            key = f.read()
            apns_key_client = APNs(
                key=key,
                key_id='<KEY_ID>',
                team_id='<TEAM_ID>',
                topic='<APNS_TOPIC>',  # Bundle ID
                use_sandbox=False,
            )
    
        # Construct the notification request
        request = NotificationRequest(
            device_token='<DEVICE_TOKEN>',
            message = {
                "aps": {
                    "alert": "Hello from APNs",
                    "badge": "1",
                }
            },
            notification_id=str(uuid4()),  # optional
            time_to_live=3,                # optional
            push_type=PushType.ALERT,      # optional
        )
    
        # Send the notifications
        await apns_cert_client.send_notification(request)
        await apns_key_client.send_notification(request)
    
    if __name__ == "__main__":
        asyncio.run(run())
  2. Configure NotificationRequest parameters

    master

    The NotificationRequest class is used to define the payload and metadata for a push notification.

    Key parameters include:

    • device_token: The target device's token.
    • message: A dictionary containing the APNs payload (e.g., {"aps": {"alert": "..."]}).
    • notification_id: An optional unique identifier for the notification.
    • time_to_live: An optional integer setting the TTL (Time To Live) for the notification.
    • push_type: An optional PushType enum value (e.g., PushType.ALERT).
  3. Send a notification with send_notification()

    master

    Use the send_notification method to dispatch a push notification. It takes a NotificationRequest object and returns a NotificationResult.

    If the notification is unsuccessful (i.e., response.is_successful is False), the client will either execute the err_func callback provided during initialization or log an error to the logger.

    Method Signature

    async def send_notification(self, request: NotificationRequest) -> NotificationResult

    from aioapns import APNs
    from aioapns.common import NotificationRequest
    
    async def main():
        client = APNs(key="key.p8", key_id="ID", team_id="TEAM", topic="com.app")
        
        request = NotificationRequest(
            # ... populate request fields ...
        )
        
        result = await client.send_notification(request)
        
        if result.is_successful:
            print("Notification sent successfully!")
        else:
            print(f"Failed: {result.status} - {result.description}")
  4. Initialize the APNs client

    master

    The APNs class is the primary entry point for sending push notifications. It manages a connection pool and supports two authentication methods: Certificate-based or Token-based (using a .p8 key).

    Authentication Methods

    1. Certificate-based: Provide client_cert. You cannot provide a key if client_cert is specified.
    2. Token-based (Key): Provide key, key_id, team_id, and topic.

    Initialization Parameters

    ParameterTypeDescription
    client_certOptional[str]Path to the client certificate file.
    keyOptional[str]Path to the .p8 private key file.
    key_idOptional[str]The Key ID provided by Apple.
    team_idOptional[str]Your Apple Developer Team ID.
    topicOptional[str]The push topic (usually the bundle ID).
    max_connectionsintMaximum number of concurrent connections (default: 10).
    max_connection_attemptsintMaximum attempts to establish a connection (default: 5).
    use_sandboxboolSet to True to use the APNs sandbox environment (default: False).
    no_cert_validationboolIf True, skips SSL certificate validation.
    ssl_contextOptional[SSLContext]A custom ssl.SSLContext instance.
    proxy_hostOptional[str]Hostname of a proxy server.
    proxy_portOptional[int]Port of a proxy server.
    err_funcOptional[Callable]An async callback function (request, result) -> None called when a notification fails.
    from aioapns import APNs
    
    # Example: Token-based authentication (Recommended)
    client = APNs(
        key="path/to/AuthKey_ABC123.p8",
        key_id="ABC123DEFG",
        team_id="TEAMID1234",
        topic="com.example.app"
    )
    
    # Example: Certificate-based authentication
    client = APNs(
        client_cert="path/to/client.pem",
        topic="com.example.app"
    )