M.Shaikh
M.Shaikh

Reputation: 250

How do we call a function each time an api end-point is called in django

In my Django server, there is an rest api through which we are saving the values in the database. If the name exists in the database then I update the value or else will create a new value and name. The code for the function is given below:

def getIgnitionData():
    name_list =[]
    value_list =[]
    cursor = connections['ignition'].cursor()
    cursor.execute('SELECT * FROM MDA_table')
    value = cursor.fetchall()
    cursor.execute('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = \'MDA_table\'')
    name = cursor.fetchall()

    for i in name:
        name_list.append(str(i[0]))


    for row in value:
        for j in row:
            value_list.append(str(j))

    cursor.close()
    print name_list
    print value

    #Here we will check to see if the variable exists. If so, update the value. If not,
    #then create a new variable.
    for k in range(0,len(name_list)):
        if (Ignition.objects.filter(name = name_list[k]).exists()):
            Ignition.objects.filter(name=name_list[k]).update(value = value_list[k])
        else:
            Ignition.objects.create(name=name_list[k], value=value_list[k])

The view_api.py is as follows:

class IgnitionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows to view variables from the ignition database.
    """
    serializer_class = IgnitionSerializer
    #queryset = ignition.objects.all()
    permission_classes = [HasGroupPermission]
    required_groups = {
        'GET': ['Admin', 'Facility', 'Operator'],
        'PUT': [],
        'POST': [],
    }
    ignition.getIgnitionData() # This is where we are calling the function 
    def get_queryset(self):
        return Ignition.objects.all()

The code works well when I run the get request for the first time from the browser, but then if I update the values in the database without restarting the server then it doesn't even print the name_list (which means it doesn't call the code). If I restart the server and access the end point, then it does fetch the updated values. This is not practical though.

I wanted that whenever I call the api endpoint it fetches the updated values from the database so that I don't have to restart the server every time. Thanks in advance.

Upvotes: 0

Views: 1293

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You can override dispatch() method which is calling each time your view is using:

class IgnitionViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows to view variables from the ignition database.
    """
    serializer_class = IgnitionSerializer
    #queryset = ignition.objects.all()
    permission_classes = [HasGroupPermission]
    required_groups = {
        'GET': ['Admin', 'Facility', 'Operator'],
        'PUT': [],
        'POST': [],
    }

    def dispatch(self, request, *args, **kwargs):
        ignition.getIgnitionData() # This is where we are calling the function 
        return super(IgnitionViewSet, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        return Ignition.objects.all()

Upvotes: 3

Related Questions