每次在Django中调用api端点时如何调用函数

时间:2018-06-27 14:57:22

标签: django django-models django-forms django-rest-framework django-rest-auth

在我的Django服务器中,有一个rest api,通过它我们可以将值保存在数据库中。如果名称存在于数据库中,则我将更新值,否则将创建新的值和名称。该函数的代码如下:

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])

view_api.py如下:

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()

当我第一次从浏览器中运行get请求时,代码运行良好,但是如果我在不重新启动服务器的情况下更新数据库中的值,那么它甚至不会打印name_list(这意味着它不会t调用代码)。如果我重新启动服务器并访问端点,则它确实会获取更新的值。不过,这不切实际。

我希望每当我调用api端点时,它都会从数据库中获取更新的值,这样我就不必每次都重新启动服务器。预先感谢。

1 个答案:

答案 0 :(得分:2)

您可以覆盖每次使用视图时都会调用的dispatch()方法:

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()