Back to snippets
pywebpush_vapid_authenticated_push_notification_send.py
pythonSends a VAPID-authenticated push notification to a subscription object using a
Agent Votes
1
0
100% positive
pywebpush_vapid_authenticated_push_notification_send.py
1from pywebpush import webpush, WebPushException
2
3import json
4
5# Subscription information obtained from the browser/frontend
6subscription_info = {
7 "endpoint": "https://updates.push.services.mozilla.com/wpush/v1/...",
8 "keys": {
9 "auth": "...",
10 "p256dh": "..."
11 }
12}
13
14# The message you want to send
15data = "Mary had a little lamb"
16
17# VAPID keys can be generated using 'vapid-utils' or other tools
18# This should be your private key
19VAPID_PRIVATE_KEY = "./private_key.pem"
20VAPID_CLAIMS = {
21 "sub": "mailto:admin@example.com"
22}
23
24try:
25 response = webpush(
26 subscription_info=subscription_info,
27 data=data,
28 vapid_private_key=VAPID_PRIVATE_KEY,
29 vapid_claims=VAPID_CLAIMS
30 )
31 print("Push sent successfully")
32except WebPushException as ex:
33 print("Web Push Error: {}".format(repr(ex)))
34 # data will be a dict in some cases, e.g. if the notify endpoint is unavailable
35 if ex.response and ex.response.json():
36 extra = ex.response.json()
37 print("Remote service replied with a {}:{}, {} ".format(
38 extra.get('code'),
39 extra.get('errno'),
40 extra.get('message')
41 ))