HomePythonDjangoFirebase Push Notification with python

Firebase Push Notification with python

so in this blog we will see how to implement fcm or Firebase Cloud Messaging services.

So what FCM is in simple words is it is used for sending messages at free of cost across different platforms like android, ios, web browser and even in fcm it’s main purpose is used for sending push notifications which are send across different mobile devices of different platform.

so below we are going to see how to implement fcm push notification with python and also one of its framework Django for android platform

so firstly for python install fcm with

pip install pyfcm

Now firstly to use fcm we need to generate a legacy token and api key of firebase

so open https://firebase.google.com/ in browser login with your account

Click on create a project and follow the rest process to create your fcm keys and token

Next step is the coding part so for simple python see the code below

from pyfcm import FCMNotification
 
push_service = FCMNotification(api_key="<api-key>")
 
push_service = FCMNotification(api_key="<api-key>")
 
 
registration_id = "<device registration_id>"
message_title = "Title"
message_body = "Hello"
result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body)
 
print (result)
 
# Send to multiple devices by passing a list of ids.
registration_ids = ["<device registration_id 1>", "<device registration_id 2>" ----]
message_title = "Title multiple"
message_body = "Hello world!"
result=push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)
 
print (result)

the above code will send push notification of message defined above to single or multiple devices based on registration

Now the above is for simple python which in most case nobody is going to use this approach without a Framework so now let’s see now for Django framework implementation

Now for Django begin with installing fcm with pip command

pip install fcm-django

then edit your settings.py file

Now fcm Django is a bit tricky or u can say the approach is a bit different from simple python approach so first run the migrate command

 python manage.py migrate

Now if you see your database you will find a new table in there called

fcm_django_device

inside that table, you will find some predefined columns like below

in the above image except for user_id all others come predefined from fcm

so now to use fcm in django the catch is you have to store the registration_id in this particular table and fetch from this particular table to use or send push notification you cannot define it in some other table and use it from there it will have to be defined in this particular table

let me give you an example lets say we have a user table and every user can have a mobile device and registration id so what i did is created user table and added fields for registration id so we can simply send the the message to that user from its regstration id of fcm right seems simple but when you follow this approach nothing will happen

so for it to work you have to create a link of user to this fcm table with foreign key and store and retrieve the fcm registration id from there to use it

below is a simple code i wright for one of my application

#for registration

from fcm_django.models import FCMDevice


class UserRegister(APIView):
    def post(self, request):
        serializer = UserRegisterSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            user = serializer.save()
            if user:
                token = Token.objects.create(user=user)
                json = serializer.data
                fcm_token = json['fcm_token']
                user = json['id'] 
                device = FCMDevice()
                device.registration_id = fcm_token
                device.type = "Android"
                device.name = "Can be anything"
                device.user = user
                device.save()
                return Response(
                    {
                        "token": token.key,
                        "error": False
                    },
                    status=status.HTTP_201_CREATED)
        else:
            data = {"error": True, "errors": serializer.errors}

            return Response(data, status=status.HTTP_400_BAD_REQUEST)


# where fcm_token is requested in json 
#for login

class UserAuth(APIView):
    def post(self, request):
        fcm = request.data.get("fcm_token")
        user = authenticate(email=request.data.get("email"),
                            password=request.data.get("password"))
        if user is not None:
            ser = UserDetailSerializer(user)
            fb = User.objects.get(id=user.id)
            print(ser.data['id'])
            try:
                devices = FCMDevice.objects.get(user=ser.data['id'])
            except FCMDevice.DoesNotExist:
                devices = None
            if devices is None:
                device = FCMDevice()
                device.user = user
                device.registration_id = fcm
                device.type = "Android"
                device.name = "Can be anything"
                device.save()
            else:
                devices.registration_id = fcm
                devices.save()
            try:
                token = Token.objects.get(user_id=user.id)
            except:
                token = Token.objects.create(user=user)
                print(token.key)
                print(user)

            return Response({"token": token.key, "error": False})
        else:
            data = {
                "error": True,
                "msg": "User does not exist or password is wrong"
            }

            return Response(data, status=status.HTTP_401_UNAUTHORIZED)

The above will do for register login of fcm keys now for implementation see below

from fcm_django.models import FCMDevice

devices = FCMDevice.objects.get(user=user_id)
devices.send_message(title="Notification",body="Hello user")

Now what above code will do is it will get the device credentials of user based on their user id which we stored in FCMDevice table via foreign key relation to the user and then will send a push notification based on the registered id of the user

Now that’s all the implementation of FCM or push notification in regards to Django framework

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: