python - 如何在fcm-django的FCMDevice上注册一个设备?

标签 python django firebase firebase-cloud-messaging pyfcm

我是 Django 的初学者。

引用这个链接,我安装了fcm-django并设置完成。 fcm-django doc

  • 安装fcm-djagno
pip install fcm-django
  • settings.py 上设置 fcm-django
import firebase_admin
from firebase_admin import credentials

cred_path = os.path.join(BASE_DIR, "serviceAccountKey.json")
cred = credentials.Certificate(cred_path)
firebase_admin.initialize_app(cred)

...

INSTALLED_APPS = [
    ...
    'fcm_django',
]

...

FCM_DJANGO_SETTINGS = {
    # default: _('FCM Django')
    "APP_VERBOSE_NAME": "django_fcm",
    # Your firebase API KEY
    "FCM_SERVER_KEY": "AAAAsM1f8bU:APA91bELsdJ8WaSy...",
    # true if you want to have only one active device per registered user at a time
    # default: False
    "ONE_DEVICE_PER_USER": False,
    # devices to which notifications cannot be sent,
    # are deleted upon receiving error response from FCM
    # default: False
    "DELETE_INACTIVE_DEVICES": True,
}

并且,当我发布通知时,如果推送处于事件状态,我会尝试向所有设备发送推送通知。

from firebase_admin.messaging import Message, Notification
from fcm_django.models import FCMDevice

class noticeCreateView(View):
    def post(self, request, *args, **kwargs):
        title = request.POST.get('title')
        content = request.POST.get('content')
        push = request.POST.get('push')

        if push:
            message = Message(
                notification=Notification(
                    title=title,
                    body=sentence,
                ),
            )

            try:
                devices = FCMDevice.objects.all()
                devices.send_message(message)
            except Exception as e:
                print('Push notification failed.', e)

        return HttpResponseRedirect(reverse('notice_list'))

我很好奇的是,当用户安装这个应用程序时,数据是否自动添加到 FCMDevice 模型中。

如果我必须手动生成数据,我想知道如何获取 FCM 注册 token 以及如何实现向 FCMDevice 模型添加数据。

最佳答案

我有一段时间遇到同样的问题,并找到了解决此问题的方法。 在 django-fcm 的所有配置之后,当用户登录/注册时创建 FCMDevice 的设备实例并将用户保存到该实例。

引用pyrebase用于创建 registration_id(token)

在观点中 从 fcm_django.models 导入 FCMDevice

fcm_device = FCMDevice()
fcm_device.registration_id = registration_id
fcm_device.user = user
fcm_device.save()

for more reference

关于python - 如何在fcm-django的FCMDevice上注册一个设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70574404/

相关文章:

python - 如何按 Python (pandas) 中列中的出现次数对 Dataframe 进行排序

python - 使用 Colab notebook 在我们的谷歌驱动器中获取文件的可共享链接

python - .join 函数不会在循环中工作

python - 在 ListView 上测试 get_context_data() 会抛出 'AttributeError: object has no attribute ' object_list'

python Django 命名与 url 路由的位置参数

python - 表单中的 Django 数组值

python - Django 是 MVC 还是 MVT 框架?

ios - Swift3/Firebase 更新子项

javascript - 如何从 IndexDB 中获取 Firebase Auth token 以进行 Ajax 调用

firebase - cordova-plugin-fcm 使用 ios 真实设备( ionic )在 token 中给出 null