Math Tutor app

The math tutor app exposes mathematics functions using dataBridges rpc feature. The math tutor app will create an RPC server called MathServer and will expose math functions inside.

dataBridges supports 2 types of RPC interactions

  • Unary RPC: the client sends a single request and receives a single response.
  • Server streaming RPC: the client sends a single request and in return, the server sends a stream of messages.

The Math app will be exposing 2 math function as Unary RPC ( math.add, math.multiply) and 1 math function as server streaming RPC (AllMathFunction)

Exposing RPC server is supported only by dataBridges server library. Hence Tutor will be using databridges-sio-server-lib. dataBridges server sdk for NodeJS, Python, .Net allows you to design powerful realtime backend applications. These applications have access to extra dataBridges features than their corresponding client SDK's. Refer to https://dev.databridges.io/rpc/rpc.concepts.html for concepts.

Before trying this sample, follow the Setup and initialization. For more information, see the Channels Pub/Sub API reference documentation.

Download source

Download the math_tutor_app by clicking on this link

Dependencies

For this application, you will require to use databridges_sio_server_lib (dataBridges Server Library) with python.

  • Install databridges server library
  • pip3 install databridges_sio_server_lib

Create math_tutor_app.py file and open it in your favorite editor.

Copy paste below code and you are ready to run this example.

#    The math tutor app exposes mathematics functions using dataBridges rpc feature.
#    The math tutor app will create an RPC server called MathServer and will expose math functions inside.
#    
#    dataBridges supports 2 types of RPC interactions
#        Unary RPC: the client sends a single request and receives a single response.
#        Server streaming RPC: the client sends a single request and in return, the server sends a stream of messages.
#    
#    The Math app will be exposing 2 math function as Unary RPC ( math.add, math.multiply) and 1 math function as server streaming RPC (AllMathFunction)
#        
#        
#    Important Note : 
#    Exposing RPC server is supported only by dataBridges server library. Hence Tutor will be using databridges_sio_server_lib.
#    dataBridges server sdk for NodeJS, Python, .Net allows you to design powerful realtime backend applications. 
#    These applications have access to extra dataBridges features than their corresponding client SDK's.
#        
#    Refer to https://dev.databridges.io/rpc/rpc.concepts.html for concepts.


import asyncio
import json
import random

# Include dataBridges server library package
from databridges_sio_server_lib import dBridges
from databridges_sio_server_lib.exceptions import dBError

class mathTutorApp():
    def __init__(self):
        self.dbridge = None
        self.mathTutor = None
        self.sessionID = None 

    # Bind to disconnected event, to get intimation about dataBridges network disconnection.
    async def disconnected(self):
        print("Disconnected from dataBridges real-time network:")

    async def connected(self):  
        try:
            # Register RPC Server with dBrdige network.
            await self.mathTutor.register()
        except dBError as dberror:
            # Catch any registration error.
            print("MathServer registration with dataBridges network faced an exception : ", dberror.source, dberror.code, dberror.message)

        async def registrationfail(payload, metadata):
            print("MathServer registration with dataBridges network faced an exception :  ", payload.source, payload.code, payload.messagea) 

        #  Bind to server.registration.fail, This will be triggered When any registration issue is raised.
        self.mathTutor.bind("dbridges:rpc.server.registration.fail", registrationfail)

        async def registrationonline(payload, metadata):
            print("MathServer is now Online and ready for Math function processing ...")

        #  Bind to server.registration.success.
        self.mathTutor.bind("dbridges:rpc.server.online", registrationonline)   

    #  Define all exposed functions.
    async def rpc_expose_functions(self):

        # Unary RPC: the client sends a single request and receives a single response.
        async def add(inparameter, response):
            payload = inparameter["inparam"]
            payload_dict = json.loads(payload)
            print("Received add for  " + str(payload_dict["a"]) + " and  " + str(payload_dict["b"])) 

            print("Sending " + str(payload_dict["a"]) + " +  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) + float(payload_dict["b"])
            await  response.end(str(payload_dict["a"]) + " + "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)


        # Unary RPC: the client sends a single request and receives a single response.
        async def multiply(inparameter, response):
            payload = inparameter["inparam"]
            payload_dict = json.loads(payload)
            print("Received multiply for  " + str(payload_dict["a"]) + " and  " + str(payload_dict["b"])) 

            print("Sending " + str(payload_dict["a"]) + " x  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) * float(payload_dict["b"])
            await  response.end(str(payload_dict["a"]) + " x "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)

        #  Server streaming RPC: the client sends a single request and in return, the server sends a stream of messages.
        async def AllMathFunction(inparameter, response):
            payload = inparameter["inparam"]
            payload_dict = json.loads(payload)
            print("Received AllMathFunction for  " + str(payload_dict["a"]) + " and  " + str(payload_dict["b"])) 

            print("Sending " + str(payload_dict["a"]) + " +  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) + float(payload_dict["b"])
            await  response.next(str(payload_dict["a"]) + " + "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)

            print("Sending " + str(payload_dict["a"]) + " -  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) - float(payload_dict["b"])
            await  response.next(str(payload_dict["a"]) + " - "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)

            print("Sending " + str(payload_dict["a"]) + " x  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) * float(payload_dict["b"])
            await  response.next(str(payload_dict["a"]) + " x "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)

            print("Sending " + str(payload_dict["a"]) + " /  " + str(payload_dict["b"]))
            result = float(payload_dict["a"]) / float(payload_dict["b"])
            await  response.end(str(payload_dict["a"]) + " / "+ str(payload_dict["b"]) + " = "  + str(result) + " from " + self.sessionID)

        #  Bind the exposed function to mathTutor RPC server.
        self.mathTutor.regfn("add", add)
        self.mathTutor.regfn("multiply",  multiply) 
        self.mathTutor.regfn("AllMathFunction",  AllMathFunction) 


    async def MainExecute(self):
        #  Initialize dataBridges server
        self.dbridge = dBridges()

        #  Replace your application key below, which you have received from dataBridges management portal.
        #  use system variables for greater security of your keys
        self.dbridge.auth_url = "_____URL_____"

        #  Replace your authentication url below, which you have received from dataBridges management portal.
        #  example https://endpoint01.databridges.io/server/v1/authenticate
        #  use system variables for greater security of your keys
        self.dbridge.appkey = "____appKey______"

        #  Replace your application secret below, which you have received from dataBridges management portal.
        #  use system variables for greater security of your keys
        self.dbridge.appsecret = '____appSecret______';

        # lets create a sessionID
        self.sessionID = ''.join(random.choices(string.ascii_lowercase + string.digits, k=7))
        print("sessionID is " + self.sessionID);  

        #  Initialize RPC Server Maths.
        self.mathTutor = self.dbridge.rpc.init("MathTutor")

        #  Define all exposed functions
        self.mathTutor.functions = self.rpc_expose_functions

        self.dbridge.connectionstate.bind("connected", self.connected)
        self.dbridge.connectionstate.bind("disconnected", self.disconnected)

        #  Connect to dataBridges. If any runtime error it will be caught in catch().
        try:
            await self.dbridge.connect()
        except dBError as dberror:
            print("dataBridges Connection exception..: ", dberror.source, dberror.code, dberror.message)


if __name__ == '__main__':
    try:
        mathTutor = mathTutorApp()
        asyncio.run(mathTutor.MainExecute())
    except Exception as e:
        print(e)

Save your file and run python3 math_tutor_app.py from the same folder.