Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 7, 2023 14:54
Show Gist options
  • Save code-boxx/bc6aed37345ad1783cfb7d230f438120 to your computer and use it in GitHub Desktop.
Save code-boxx/bc6aed37345ad1783cfb7d230f438120 to your computer and use it in GitHub Desktop.
Python Push Notifications

PYTHON FLASK PUSH NOTIFICATIONS

https://code-boxx.com/python-flask-push-notifications/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S2_perm_sw.html inside.
    • Create a static folder, move S3_sw.js inside.
    • Save the below images as static/i-banner.png and static/i-ico.png
    • Create a virtual environment - virtualenv venv.
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install required modules - pip install flask ecdsa pywebpush
    • Run python S1_vapid.py to generate the VAPID keys.
  2. Copy the public key into templates/S2_perm_sw.html - const publicKey, and the private key into templates/S4_server.py - VAPID_PRIVATE.
  3. Run python S4_server.py, access http://localhost in your browser and allow notifications.

IMAGES

i-banner i-ico

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# (A) REQUIRED MODULES
import base64
import ecdsa
# (B) GENERATE KEYS
# CREDITS : https://gist.github.com/cjies/cc014d55976db80f610cd94ccb2ab21e
pri = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p)
pub = pri.get_verifying_key()
keys = {
"private" : base64.urlsafe_b64encode(pri.to_string()).decode("utf-8").strip("="),
"public" : base64.urlsafe_b64encode(b"\x04" + pub.to_string()).decode("utf-8").strip("=")
}
print(keys)
<!DOCTYPE html>
<html>
<head>
<title>Push Notification</title>
<meta charset="utf-8">
</head>
<body>
<script>
// (A) OBTAIN USER PERMISSION TO SHOW NOTIFICATION
window.onload = () => {
// (A1) ASK FOR PERMISSION
if (Notification.permission === "default") {
Notification.requestPermission().then(perm => {
if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
} else {
alert("Please allow notifications.");
}
});
}
// (A2) GRANTED
else if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
}
// (A3) DENIED
else { alert("Please allow notifications."); }
}
// (B) REGISTER SERVICE WORKER
async function regWorker () {
// (B1) YOUR PUBLIC KEY - CHANGE TO YOUR OWN!
const publicKey = "YOUR-PUBLIC-KEY";
// (B2) REGISTER SERVICE WORKER
navigator.serviceWorker.register("S3_sw.js", { scope: "/" });
// (B3) SUBSCRIBE TO PUSH SERVER
navigator.serviceWorker.ready
.then(reg => {
reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
}).then(
// (B3-1) OK - TEST PUSH NOTIFICATION
sub => {
var data = new FormData();
data.append("sub", JSON.stringify(sub));
fetch("/push", { method:"POST", body:data })
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
},
// (B3-2) ERROR!
err => console.error(err)
);
});
}
</script>
</body>
</html>
// (A) INSTANT WORKER ACTIVATION
self.addEventListener("install", evt => self.skipWaiting());
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());
// (C) LISTEN TO PUSH
self.addEventListener("push", evt => {
const data = evt.data.json();
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
image: data.image
});
});
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response, send_from_directory
from pywebpush import webpush, WebPushException
import json
# (A2) FLASK SETTINGS + INIT - CHANGE TO YOUR OWN!
HOST_NAME = "localhost"
HOST_PORT = 80
VAPID_SUBJECT = "mailto:your@email.com"
VAPID_PRIVATE = "YOUR-PRIVATE-KEY"
app = Flask(__name__)
# app.debug = True
# (B) VIEWS
# (B1) "LANDING PAGE"
@app.route("/")
def index():
return render_template("S2_perm_sw.html")
# (B2) SERVICE WORKER
@app.route("/S3_sw.js")
def sw():
response = make_response(send_from_directory(app.static_folder, "S3_sw.js"))
return response
# (B3) PUSH DEMO
@app.route("/push", methods=["POST"])
def push():
# (B3-1) GET SUBSCRIBER
sub = json.loads(request.form["sub"])
# (B3-2) TEST PUSH NOTIFICATION
result = "OK"
try:
webpush(
subscription_info = sub,
data = json.dumps({
"title" : "Welcome!",
"body" : "Yes, it works!",
"icon" : "static/i-ico.png",
"image" : "static/i-banner.png"
}),
vapid_private_key = VAPID_PRIVATE,
vapid_claims = { "sub": VAPID_SUBJECT }
)
except WebPushException as ex:
print(ex)
result = "FAILED"
return result
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
md templates
md static
move S2_perm_sw.html templates
move S3_sw.js static
curl https://user-images.githubusercontent.com/11156244/281081281-a7385905-0a84-4053-b19d-9584f7ba017d.png --ssl-no-revoke --output static/i-banner.png
curl https://user-images.githubusercontent.com/11156244/281081294-9878c258-0609-4da6-8abf-e855635651b2.png --ssl-no-revoke --output static/i-ico.png
virtualenv venv
call venv\Scripts\activate
pip install flask ecdsa pywebpush
python S1_vapid.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S2_perm_sw.html ./templates
mv ./S3_sw.js ./static
curl https://user-images.githubusercontent.com/11156244/281081281-a7385905-0a84-4053-b19d-9584f7ba017d.png --ssl-no-revoke --output ./static/i-banner.png
curl https://user-images.githubusercontent.com/11156244/281081294-9878c258-0609-4da6-8abf-e855635651b2.png --ssl-no-revoke --output ./static/i-ico.png
virtualenv venv
source "venv/bin/activate"
pip install flask ecdsa pywebpush
python S1_vapid.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment