我是 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()
关于python - 如何在fcm-django的FCMDevice上注册一个设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70574404/