Replace hyper by httpx to send the apns

clubs
Laurent 1 year ago
parent 9b2bd5ec50
commit 23105227c1
  1. 2
      requirements.txt
  2. 38
      tournaments/utils/apns.py
  3. 5
      tournaments/views.py

@ -6,4 +6,4 @@ django-qr-code==4.0.1
pycryptodome==3.20.0
requests==2.31.0
PyJWT==2.8.0
hyper==0.7.0
httpx[http2]==0.27.0

@ -2,7 +2,8 @@ import http.client
import json
import jwt
import time
from hyper import HTTP20Connection
import httpx
import asyncio
# APPLE WARNING: Reuse a connection as long as possible.
# In most cases, you can reuse a connection for many hours to days.
@ -35,11 +36,12 @@ bundle_id = 'app.padelclub'
# device_token = 'user_device_token'
message = 'Hello, World!'
def send_push_notification(device_token, message):
async def send_push_notification(device_token, message):
jwt_token = generate_jwt(key_path, key_id, team_id)
# APNs endpoint (use 'api.push.apple.com' for production)
host = 'api.sandbox.push.apple.com'
# host = 'api.sandbox.push.apple.com'
url = f"https://api.sandbox.push.apple.com/3/device/{device_token}"
payload = {
"aps": {
@ -51,7 +53,7 @@ def send_push_notification(device_token, message):
payload_json = json.dumps(payload)
# Create the HTTP connection
connection = HTTP20Connection(host, port=443)
# connection = HTTP20Connection(host, port=443)
# Set the headers
headers = {
@ -60,15 +62,21 @@ def send_push_notification(device_token, message):
"content-type": "application/json"
}
# Send the notification
connection.request(
"POST",
f"/3/device/{device_token}",
body=payload_json,
headers=headers
)
response = connection.get_response()
response_data = response.read()
async with httpx.AsyncClient(http2=True) as client:
response = await client.post(url, json=payload, headers=headers)
print(response.status, response.reason, response_data)
# Send the notification
# connection.request(
# "POST",
# f"/3/device/{device_token}",
# body=payload_json,
# headers=headers
# )
# response = connection.get_response()
# response_data = response.read()
if response.status_code == 200:
print("Notification sent successfully!")
else:
print(f"Failed to send notification: {response.status_code} {response.text}")

@ -16,6 +16,7 @@ from datetime import date
from django.http import JsonResponse
from django.db.models import Q
import json
import asyncio
from api.tokens import account_activation_token
@ -287,5 +288,7 @@ def download(request):
def test_apns(request):
token = DeviceToken.objects.first()
send_push_notification(token.value, 'hello!')
asyncio.run(send_push_notification(token.value, 'hello!'))
return HttpResponse('OK!')

Loading…
Cancel
Save