zoukankan      html  css  js  c++  java
  • restful规范 之 CBV 实现接口流程梳理

    一、CBV实现demo代码展示

    1、urls.py

    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path(r'^Students/$',views.StudentView.as_view()),
    ]
    

    2、views.py

    from django.shortcuts import render,HttpResponse
    
    from django.views import View
    
    class StudentView(View):
    
        def get(self,request):
            print("查看所有的学生。。。")
            return HttpResponse("查看所有的学生。。。")
    
        def post(self,request):
            print("添加一个学生。。。")
            return HttpResponse("添加一个学生。。。")
    

    3、通过postman请求接口 http://127.0.0.1:8000/Students/


    二、CBV执行过程理解 

     

     备注:

     在 StudentView(View)类的父类View下的dispatch方法理解:

    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)  # getattr(object,name,default) object: 对象;name:字符串,对象属性;default:默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs) 

    欢迎大家一起来讨论学习!!!

  • 相关阅读:
    对文本抽取词袋模型特征
    jieba分词
    家用电器用户行为分析与事件识别
    Linux系统调用:创建和终止进程
    Linux系统调用:获取进程PID
    使用函数指针解决函数重载二义性调用问题
    C++ string基本操作
    有界深度优先搜索-八数码问题
    数据传送指令
    x86-64数据格式、通用寄存器与操作数格式
  • 原文地址:https://www.cnblogs.com/rubickcn/p/14203426.html
Copyright © 2011-2022 走看看