搜索
首页后端开发Python教程使用 Django 推送通知赢得用户脱离的战斗

Winning the Battle Against User Disengagement with Django Push Notifications

在快节奏的移动应用世界中,保持用户参与度是一项挑战。今天,我们探讨 Django 如何通过设置推送通知来让用户了解情况并保持联系,从而帮助开发人员应对用户脱离的问题。

在 Django 中设置推送通知

推送通知就像一个友好的提醒,通过更新或提醒将用户带回到您的应用程序。 Django 可以通过几个基本步骤有效地处理这个问题。

第 1 步:构建通知模型

首先,Django 需要一个通知模型。此模型将存储您的应用发送给用户的所有通知。

from django.db import models
from django.utils.translation import gettext_lazy as _

class Notification(models.Model):
    title = models.CharField(max_length=255, verbose_name=_('Notification title'))
    body = models.TextField(verbose_name=_('Notification body'))
    image = models.ImageField(upload_to='notifications/', null=True, blank=True)
    created_date = models.DateTimeField(auto_now_add=True)  # Add this field

    def __str__(self):
        return self.title

    class Meta:
        ordering = ("-created_date",)  # Now created_date exists
        verbose_name = _('Notification')

第 2 步:创建发送通知函数

接下来,我们将添加一个功能来发送这些通知。这是我们编写在需要时发送消息的逻辑的地方,确保用户获得实时更新。

#notifcations.py

import os
from google.oauth2 import service_account
from google.auth.transport.requests import Request
import requests

def refresh_access_token(service_account_file):
    credentials = service_account.Credentials.from_service_account_file(
        service_account_file,
        scopes=["https://www.googleapis.com/auth/cloud-platform"],
    )
    credentials.refresh(Request())
    access_token = credentials.token
    return access_token

第 3 步:设置信号

Django 可以使用信号根据用户操作触发通知,例如新消息或已完成的任务。

from django.db.models.signals import post_save
from django.dispatch import receiver
import requests

# Import the Notification model and the refresh_access_token function
from my_app.models import Notification  # Change 'my_app' to your actual app name
from my_app.notifications import refresh_access_token  # Update the path if necessary
@receiver(post_save, sender=Notification)
def send_notification_on_creation(instance, created, **kwargs):
    if created:
        service_account_file = '/home/rv/Documents/rv/push_notification/core/my_app/test-project.json'
        tkn = refresh_access_token(service_account_file)
        print('tkn',tkn)
        endpoint = "https://fcm.googleapis.com/v1/projects/test-project-595ae/messages:send"
        access_token = tkn
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json",
        }

        data = {
            "message": {
                "token":"dnTB_cv9TZ25jsOkkQSS0x:APA91bEghK69zhqpTi2B5hPFtX0mpLSzdSQswrGEKl60PrUQDgy9RTIc_f9pjfxoyuUU-w8xjwk0WO1KtvbwF3bYFlQ21HWv-JueS-Fu7azhUsjgULDN41TTTiqONsqLsbIqS9_xKsUv",
                "notification": {
                    "title": instance.title,
                    "body": instance.body,
                }
            }
        }

        response = requests.post(endpoint, json=data, headers=headers)

        if response.status_code == 200:
            print("Push notification successfully sent!")
        else:
            print(f"Failed to send push notification. Status code: {response.status_code}")
            print(response.text)

第4步:在后台注册

最后,通过在 Django 管理面板中注册通知模型,我们可以轻松管理通知,让一切井然有序并准备就绪。

from django.contrib import admin

from .models import *

admin.site.register(Notification)

集成 Firebase 以实现前端通知
为了确保通知到达用户的设备,Django 与 Firebase 合作。

以上是使用 Django 推送通知赢得用户脱离的战斗的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python:编译器还是解释器?Python:编译器还是解释器?May 13, 2025 am 12:10 AM

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

python用于循环与循环时:何时使用哪个?python用于循环与循环时:何时使用哪个?May 13, 2025 am 12:07 AM

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

Python循环:最常见的错误Python循环:最常见的错误May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

对于循环和python中的循环时:每个循环的优点是什么?对于循环和python中的循环时:每个循环的优点是什么?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。