python web应用_如何使用Python将通知发送到Web应用

python web应用

by Lucas Hild

卢卡斯·希尔德(Lucas Hild)

如何使用Python将通知发送到Web应用 (How to send notifications to your Web App using Python)

Native apps have become hugely popular recently, mostly because of features such as working offline, transitions, easy distributability and of course push notifications. But unfortunately, you need a good knowledge of languages like Java or Swift to create a valuable native app.

本地应用程序最近变得非常流行,主要是因为具有诸如脱机工作,过渡,易于分发以及当然还有推送通知之类的功能。 但是不幸的是,您需要对Java或Swift等语言有充分的了解才能创建有价值的本机应用程序。

渐进式Web应用 (Progressive Web Apps)

Progressive Web Apps (PWAs) are JavaScript applications that run in the browser. They make the effort to bring some of the native app features to the web. PWAs are easy to develop if you have a fundamental knowledge of HTML, CSS, and in particular JavaScript. Moreover, if your service is already accessible for desktop devices on a website, it is easier to add the functionalities of a Web App, instead of developing a native mobile app.

渐进式Web应用程序(PWA)是在浏览器中运行JavaScript应用程序。 他们努力将一些本机应用程序功能引入网络。 如果您具有HTML,CSS尤其是JavaScript的基础知识,则PWA易于开发。 此外,如果网站上的桌面设备已经可以访问您的服务,则添加Web应用程序的功能要比开发本机移动应用程序容易得多。

通知事项 (Notifications)

Notifications keep users informed about new messages, tell them about a new blog post, and so on.

通知可让用户了解新消息,将新博客内容告诉他们,等等。

Many native apps send push notifications to the user. But this is also possible using PWAs and the Notifications API.

许多本机应用程序将推送通知发送给用户。 但这也可以使用PWA和Notifications API来实现。

OneSignal (OneSignal)

In this tutorial, we will be using OneSingal to send notifications to our web app. OneSignal is a powerful tool that provides a simple interface to push notifications. They also provide a Rest API, which we will be using to send notifications.

在本教程中,我们将使用OneSingal将通知发送到我们的Web应用程序。 OneSignal是功能强大的工具,提供了用于推送通知的简单界面。 他们还提供了Rest API,我们将使用该API发送通知。

设置OneSignal (Setup OneSignal)

To send push notifications, you need to setup OneSignal first. Therefor you need an account on OneSignal. Head over to their website and press “Log in” in the upper right corner.

要发送推送通知,您需要先设置OneSignal。 因此,您需要在OneSignal上拥有一个帐户。 转到他们的网站 ,然后按右上角的“登录”。

Next you will have to create an app. Give it a name and choose “Setup platform”. Here you select “All Browsers”. After that, you choose “custom code” as the integration. Then you have to provide some information about your website.

接下来,您将必须创建一个应用。 给它起一个名字,然后选择“安装平台”。 在这里,您选择“所有浏览器”。 之后,选择“自定义代码”作为集成。 然后,您必须提供有关您的网站的一些信息。

In the settings area of your app, there is a tab called “Keys & IDs”. Copy both keys for later.

在应用程序的设置区域中,有一个名为“密钥和ID”的标签。 复制两个密钥以供以后使用。

Important: Do not share you REST API Key. Keep it private!

重要提示:不要共享您的REST API密钥。 保持私密!

That’s it for setting up OneSignal. That was easy!

设置OneSignal就是这样。 那很简单!

设置我们的网站 (Setup our website)

In the next part, we will be adding the notification functionality to our website. The website will have to wait for notifications sent by OneSignal and display them to the user.

在下一部分中,我们将向网站添加通知功能。 该网站将必须等待OneSignal发送的通知并将其显示给用户。

To let the browser know that you are creating a Progressive Web App, we will add a file called manifest.json to the root of our project.

为了让浏览器知道您正在创建渐进式Web应用程序,我们将在项目的根目录中添加一个名为manifest.json的文件。

{  "name": "My Application",  "short_name": "Application",  "start_url": ".",  "display": "standalone",  "background_color" : "#fff" ,  "description": "We send notifications to you",  "gcm_sender_id": "482941778795",  "gcm_sender_id_comment": "Do not change the GCM Sender ID"}

The first six key-value-pairs describe the appearance of the application. The gcm_send_id is important for sending notifications. If you want to know more about manifest.json, you can have a look in the Mozilla Documentation.

前六个键值对描述了应用程序的外观。 gcm_send_id对于发送通知很重要。 如果您想了解有关manifest.json的更多信息,请查看Mozilla文档

Your browser doesn’t automatically look for the manifest. You have to put the path to it in every HTML document in the <head> tag.

您的浏览器不会自动查找清单。 您必须在 lt; h e >广告代码中的每个HTML文档中放置路径。

<head>    ...    <link rel="manifest" href="manifest.json">    ...</head>

Additionally, we need some JavaScript code to connect our website to OneSignal.

此外,我们需要一些JavaScript代码才能将我们的网站连接到OneSignal。

You can put the code for that in a script tag in the &lt;head> part. Don’t forget to replace my-app-id with your own OneSignal app id.

你可以把代码在一个脚本标签在&lt; 广告>部分。 不要忘了重新的地方我- APP-ID与自己的OneSignal应用程序ID。

<head>    <script src="https://cdn.onesignal.com/sdks/OneSignalSDK.js" async=""></script>        <script>        var OneSignal = window.OneSignal || [];        OneSignal.push(function () {            OneSignal.init({                appId: "my-app-id",                autoRegister: false,                notifyButton: {                    enable: true,                },            });        });    <script></head>

When you want to prompt the user to subscribe to your notifications, you execute this piece of code.

当您想提示用户订阅您的通知时,您可以执行这段代码。

OneSignal.push(function () {    OneSignal.showHttpPrompt();});

Moreover, you need a service worker, which listens in the background for notifications. Therefore, you need two files in the root directory of your project.

此外,您需要一名服务人员,该服务人员在后台侦听通知。 因此,您在项目的根目录中需要两个文件。

OneSignalSDKUpdaterWorker.js

OneSignalSDKUpdaterWorker.js

importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');

OneSignalSDKWorker.js

OneSignalSDKWorker.js

importScripts('https://cdn.onesignal.com/sdks/OneSignalSDKWorker.js');

使用Python访问API (Access the API using Python)

OneSignal has an easy-to-use Rest API. The endpoints are documented in the OneSignal Developer Documentation.

OneSignal具有易于使用的Rest API。 端点记录在OneSignal开发人员文档中

To access it, we need to send HTTP requests. Therefore, we will use a library called requests. To install it, you can use pip, the package manager of Python.

要访问它,我们需要发送HTTP请求。 因此,我们将使用一个称为request的库。 要安装它,可以使用Python的包管理器pip。

pip install requests

This is the API endpoint we need to send a notification: https://onesignal.com/api/v1/notifications.

这是我们需要发送通知的API端点: https : //onesignal.com/api/v1/notifications

The HTTP protocol has several methods. In this case, we want to make a POST request. To do so, we need to import requests and execute a function.

HTTP协议有几种方法。 在这种情况下,我们要发出POST请求。 为此,我们需要导入请求并执行一个函数。

import requests
requests.post("https://onesignal.com/api/v1/notifications")

OneSignal wants to verify that only you can send notifications to your website. So you have to add an HTTP header with your Rest API Key from OneSignal.

OneSignal希望验证只有您可以将通知发送到您的网站。 因此,您必须使用OneSignal的Rest API密钥添加HTTP标头。

requests.post(    "https://onesignal.com/api/v1/notifications",    headers={"Authorization": "Basic my-rest-api-key"})

Remember to replace my-rest-api-key with your Rest API Key.

请记住用您的Rest API密钥替换my-rest-api-key

Moreover, you need some basic information about your notification.

此外,您需要有关通知的一些基本信息。

data = {    "app_id": "my-app-id",    "included_segments": ["All"],    "contents": {"en": "Hello"}}
requests.post(    "https://onesignal.com/api/v1/notifications",    headers={"Authorization": "Basic my-rest-api-key"},    json=data)

Replace my-app-id with your own app id. Next you choose who will receive your notifications. Example values are "All", "Active Users", "Inactive Users”. But you can also create your own segments. And for the last one, you add some content of the message in English. If you need another language, you can add it here too.

my-app-id替换为您自己的应用程序ID。 接下来,您选择谁将收到您的通知。 值的示例是"All", "Active Users", "Inactive Users” ,但您也可以创建自己的细分。最后一个,您可以用英语添加一些消息内容。如果您需要其他语言,则可以也将其添加到此处。

That’s it! If you subscribed to the notifications, you should get a push notification.

而已! 如果您订阅了这些通知,则应该收到推送通知。

使用API​​包装器发送通知 (Send notifications using an API Wrapper)

Because my code became kind of messy with many different notifications, I created an API wrapper for OneSignal.

因为我的代码因许多不同的通知而变得混乱,所以我为OneSignal创建了API包装器

API包装器 (API Wrapper)

But what is an API wrapper? An API wrapper makes it easier for you to access an API. You can say that it is an API for an API. You call the API wrapper instead of the API directly.

但是什么是API包装器? API包装器使您可以更轻松地访问API。 您可以说这是API的API。 您调用API包装器,而不是直接调用API。

You can install the wrapper called OneSignal-Notifications from pip.

您可以从pip安装称为OneSignal-Notifications的包装器。

pip install onesignal-notifications

Now you can import it and setup your client.

现在,您可以导入它并设置您的客户端。

from onesignal import OneSignal, SegmentNotificationclient = OneSignal("MY_APP_ID", "MY_REST_API_KEY")

To send a Notification, you have to initialize the class SegmentNotification and use the method send.

要发送通知,您必须初始化SegmentNotification 并使用send方法。

notification_to_all_users = SegmentNotification(    {        "en": "Hello from OneSignal-Notifications"    },    included_segments=SegmentNotification.ALL)client.send(notification_to_all_users)

Maybe this looks kind of unnecessary to you, because it takes even more lines of code. But if you have several notifications, it makes the process much easier and your code more beautiful.

对于您来说,这似乎不必要,因为它需要更多的代码行。 但是,如果您有多个通知,它将使处理过程变得更加容易,代码也将变得更漂亮。

For example if you want to send a notification, which is based on some conditions, the API wrapper has a custom class for that.

例如,如果您要发送基于某些条件的通知,则API包装器为此具有一个自定义类。

from onesignal import OneSignal, FilterNotification, Filterclient = OneSignal("MY_APP_ID", "MY_REST_API_KEY")
filter_notification = FilterNotification(    {        "en": "Hello from OneSignal-Notifications"    },    filters=[        Filter.Tag("my_key", "<", "5"),        "AND",        Filter.AppVersion(">", "5"),        "OR",        Filter.LastSession(">", "1"),    ])

There are many custom parameters you can provide to adapt your notification. For example, you can add buttons to the notification. All list of all parameters can be found here.

您可以提供许多自定义参数来适应您的通知。 例如,您可以在通知中添加按钮。 所有参数的所有列表都可以在此处找到。

from onesignal import OneSignal, FilterNotification, Filterclient = OneSignal("MY_APP_ID", "MY_REST_API_KEY")
filter_notification = SegmentNotification(    {        "en": "Hello from OneSignal-Notifications"    },    web_buttons=[        {          "id": "like-button",          "text": "Like",          "icon": "http://i.imgur.com/N8SN8ZS.png",          "url": "https://github.com/Lanseuo/onesignal-notifications"}    ],    included_segments=SegmentNotification.ALL)

If you want to find out more about OneSignal-Notifications, you can have a look in the GitHub Repository or in the docs.

如果您想了解有关OneSignal-Notifications的更多信息,可以在GitHub Repositorydocs中查看。

翻译自: https://www.freecodecamp.org/news/how-to-send-notifications-to-your-web-app-using-python-ba490b893292/

python web应用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值