[updated] Webpush Notifications using ONLY Anvil and Python

I managed to get OneSignal notifications work from a python call using a OneSignal Python SDK.

So the steps:

  1. Transform the Anvil webapp to a native app with webtonative.com
    1.1 Setup OneSignal when creating the app
    1.2 You need to connect firebase, but firebase is not really used
  2. download and install the app on your phone
  3. Put the following code in an Anvil app or background task to do a push notification.
from onesignal_sdk.client import Client

# Initialize OneSignal client
client = Client(app_id="your app id from Onesignal",
                          rest_api_key="rest api key from Onesignal app",
                          user_auth_key=" can be found in your personal settings")


@anvil.server.callable
def push_onesignal():
  print(client)
  try:
    notification_body = {
      'contents': {'en': 'New notification'},
        'included_segments': ['All'],
      #'filters': [],
    }
    response = client.send_notification(notification_body)
    print(response.body)

  except Exception as e:
      print(f"Error sending push notification: {e}")

This sends a push notification to all app installers. Something I can’t seem to figure out is how to get the “device id”, “player id” or “onesignal_id” (basicly whatever id that is unique to the user/install).

So that we can send push notification to certain users, and put that user id in our anvil user database.

There is another project: onesignal js and anvil but they use the js api. Which is not pure python.

There are also different onesignal python sdk’s, others I have not been able to make them work.

1 Like