44https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html
55"""
66
7+ import contextlib
78import time
89
910from apns2 import client as apns2_client
1617from .exceptions import APNSError , APNSUnsupportedPriority , APNSServerError
1718
1819
20+ @contextlib .contextmanager
1921def _apns_create_socket (application_id = None ):
2022 if not get_manager ().has_auth_token_creds (application_id ):
2123 cert = get_manager ().get_apns_certificate (application_id )
@@ -34,7 +36,7 @@ def _apns_create_socket(application_id=None):
3436 use_alternative_port = get_manager ().get_apns_use_alternative_port (application_id )
3537 )
3638 client .connect ()
37- return client
39+ yield client
3840
3941
4042def _apns_prepare (
@@ -60,8 +62,6 @@ def _apns_prepare(
6062def _apns_send (
6163 registration_id , alert , batch = False , application_id = None , ** kwargs
6264):
63- client = _apns_create_socket (application_id = application_id )
64-
6565 notification_kwargs = {}
6666
6767 # if expiration isn"t specified use 1 month from now
@@ -78,23 +78,24 @@ def _apns_send(
7878
7979 notification_kwargs ["collapse_id" ] = kwargs .pop ("collapse_id" , None )
8080
81- if batch :
82- data = [apns2_client .Notification (
83- token = rid , payload = _apns_prepare (rid , alert , ** kwargs )) for rid in registration_id ]
84- # returns a dictionary mapping each token to its result. That
85- # result is either "Success" or the reason for the failure.
86- return client .send_notification_batch (
87- data , get_manager ().get_apns_topic (application_id = application_id ),
81+ with _apns_create_socket (application_id = application_id ) as client :
82+ if batch :
83+ data = [apns2_client .Notification (
84+ token = rid , payload = _apns_prepare (rid , alert , ** kwargs )) for rid in registration_id ]
85+ # returns a dictionary mapping each token to its result. That
86+ # result is either "Success" or the reason for the failure.
87+ return client .send_notification_batch (
88+ data , get_manager ().get_apns_topic (application_id = application_id ),
89+ ** notification_kwargs
90+ )
91+
92+ data = _apns_prepare (registration_id , alert , ** kwargs )
93+ client .send_notification (
94+ registration_id , data ,
95+ get_manager ().get_apns_topic (application_id = application_id ),
8896 ** notification_kwargs
8997 )
9098
91- data = _apns_prepare (registration_id , alert , ** kwargs )
92- client .send_notification (
93- registration_id , data ,
94- get_manager ().get_apns_topic (application_id = application_id ),
95- ** notification_kwargs
96- )
97-
9899
99100def apns_send_message (registration_id , alert , application_id = None , ** kwargs ):
100101 """
0 commit comments