[Django] My understanding of dispatch

views.py

import json

from django.http import JsonResponse
from django.views import View
from myapp.models import UserKey


class Mysql_data(View):
    def dispatch(self, request, *args, **kwargs):
        action = kwargs.pop('action', None)
        if action == 'get_mysql_data':
            return self.mymodel_list(request, *args, **kwargs)
        if action == 'delete_data':
            return self.delete_data(request, *args, **kwargs)

    @staticmethod
    def mymodel_list(request):
        # values() 方法用于查询字段的数据。
        data = list(UserKey.objects.all().values())
        print(data)
        return JsonResponse({'my_data': data})

    @staticmethod
    def delete_data(request):
        mysql_data = json.loads(request.body)
        print(mysql_data)
        print(type(mysql_data))
        # # 根据id获取要删除的数据
        data = UserKey.objects.get(pk=mysql_data)
        # 删除数据
        a = data.delete()
        print(a)
        b = list(a)
        return JsonResponse({'status_code': 200, 'my_data': b})

focus

class Mysql_data(View):
    def dispatch(self, request, *args, **kwargs):
        action = kwargs.pop('action', None)
        if action == 'get_mysql_data':
            return self.mymodel_list(request, *args, **kwargs)
        if action == 'delete_data':
            return self.delete_data(request, *args, **kwargs)

The rest of this code is fixed, mainly depends on the if statement and its return value. When the action is equal to send_message, the main() function is called, and when the action is equal to check_message, the post() function is called. How to judge his action? This needs to be set in urls.py:

urls.py

from django.urls import path

from myapp.mysql_data import Mysql_data


# # 短信验证登录路由
urlpatterns = [
    # 显示数据库数据
    path('mysql_data/', Mysql_data.as_view(), {"action": "get_mysql_data"}),
    path('delete_data/', Mysql_data.as_view(), {"action": "delete_data"})
]

(FBV is generally used for the call of a single function and its route, and CBV is used for two or more function call routes. The above urls.py uses Django's CBV development method. See the rookie tutorial for details;)

In path(), action is used to identify it. So when mysql_data/ routing is called, the mymodel_list function will be executed , and when delete_data/ routing is called, the delete_data function will be called ;

Guess you like

Origin blog.csdn.net/weixin_65690979/article/details/132045847