当前位置: 首页 > article >正文

二、初步编写drf API

2.1基于django

#settings.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth',views.auth)                       #创建一个路由
]
#views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

# Create your views here.

@csrf_exempt
def auth(request):
    return JsonResponse({'status':True,'message':'success'})

使用postman测试,可以看到有返回数据

在这里插入图片描述

2.2基于drf

1.安装drf

pip3 install djangorestframework

2.注册drf

#settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app1.apps.App1Config',  # 添加应用名称(appName.apps.className)
    'rest_framework',        #注册drf
  
]

3、注册路由

#url.py
urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/',views.auth),
    path('login1/',views.login)#drf视图路由(方法1:FBV)
    path('login2/',views.LoginView.as_view())       #drf视图路由(方法2:CBV)
]

4、创建drf视图函数

#方法1:FBV: function basic views(基于函数的视图)
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.decorators import api_view

@api_view(['GET'])                #视图函数前面需要加上一个装饰器
def login(request):
    return Response({'status':True,'message':'success'})
#方法2:CBV: class basic views(基于类的视图)
class LoginView(APIView):
    def get(self,request):
        return Response({'status': True, 'message': 'success'})

5、查看效果

用浏览器访问login,这里可以看到,Response返回的信息,被drf的基本页面包裹(以上两种方法效果相同)
在这里插入图片描述

6、CBV示例1(jdango)

from django.http import JsonResponse
from django.views import View
class UserView(View):
    #不同的请求,执行不同的值
    def get(self,request):
        #get请求执行的函数
        return JsonResponse({'status': True, 'message': 'GET'})
    def post(self,request):
        #post请求执行的函数
        return JsonResponse({'status': True, 'message': 'POST'})
    def put(self,request):
        #put请求执行的函数
        return JsonResponse({'status': True, 'message': 'PUT'})
    def delete(self,request):
        #delete请求执行的函数
        return JsonResponse({'status': True, 'message': 'DELETE'})

7、CBV示例2(drf)

from rest_framework.response import Response
from rest_framework.views import APIView

class UserView1(APIView):  #drf中的函数自动套用了免除CRSF认证,相当于会自动给函数加一个@csrf_exempt装饰器
    def get(self,request):
        return Response({'status': True, 'message': 'GET'})
    def post(self,request):
        return Response({'status': True, 'message': 'POST'})
    def put(self,request):
        return Response({'status': True, 'message': 'PUT'})
    def delete(self,request):
        return Response({'status': True, 'message': 'DELETE'})
#APIView底层代码
 def as_view(cls, **initkwargs):
        """
        用于免除CRSF认证
        Store the original class on the view function.

        This allows us to discover information about the view when we do URL
        reverse lookups.  Used for breadcrumb generation.
        """
 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.

http://www.kler.cn/news/323808.html

相关文章:

  • 太速科技-389-基于KU5P的双路100G光纤网络加速计算卡
  • linux系统的常用命令
  • 【系统规划与管理师】【案例分析】【考点】【答案篇】第10章 团队建设与管理
  • docker相关命令
  • 基于单片机的精确电压表DA-AD转换
  • 【笔记】神领物流day1.1.13前后端部署【未完】
  • JVM、JRE、JDK关系。HotSpot。JVM规范
  • 【R语言】fs 工具功能速查
  • 【项目经验分享】深度学习点云算法毕业设计项目案例定制
  • 【JavaEE】——内存可见性问题
  • 支付宝远程收款api之小荷包跳转码
  • 画两个数的平方和的曲线
  • ECharts图表图例3
  • 【记录】Excel|不允许的操作:合并或隐藏单元格出现的问题列表及解决方案
  • el-table给列加单位,表头加样式,加斑马纹
  • 【YashanDB知识库】如何dump数据文件,转换rowid, 查询对应内容
  • 9月27日,每日信息差
  • XSS基础
  • 蓝桥杯—STM32G431RBT6(TIM定时器输入捕获频率和占空比)
  • 北斗三号多模对讲机TD70:公专网融合、数模一体、音视频调度,推动应急通信效能升级
  • Xiaojie雷达之路---doa估计(dbf、capon、music算法)
  • 通信工程学习:什么是MIMO多输入多输出技术
  • TDSQL-C电商可视化,重塑电商决策新纪元
  • 我可以通过发包拿到视频网站的视频源文件吗?
  • 软件设计之SSM(1)
  • PWM基础与信号控制
  • C++动态规划问题—第 N 个泰波那契数
  • 物联网助力智慧交通:优势与前景
  • ScrapeGraphAl AI爬虫
  • 零基础教你如何开发webman应用插件