• Django REST framework框架介绍和基本使用


    Django REST framework介绍

    Django REST framework是基于Django实现的一个RESTful风格API框架,能够帮助我们快速开发RESTful风格的API。

    官网:https://www.django-rest-framework.org/

    中文文档:https://q1mi.github.io/Django-REST-framework-documentation/

    Django REST framework安装与配置

    安装

    pip install djangorestframework

    配置

    如果想要获取一个图形化的页面,需要将 rest_framework 注册到项目的INSTALL_APPS中。

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'bms.apps.BmsConfig',
        'rest_framework',
    ]

    基于Django实现RESTful API

    路由

    urlpatterns = [
        url(r'^users', Users.as_view()),
    ]

    视图

    from django.views import View
    from django.http import JsonResponse
     
    class Users(View):
        def get(self, request, *args, **kwargs):
            result = {
                'code': 0,
                'data': 'response data'
            }
            return JsonResponse(result, status=200)
     
        def post(self, request, *args, **kwargs):
            result = {
                'code': 0,
                'data': 'response data'
            }
            return JsonResponse(result, status=200) 

    基于Django REST Framework框架实现

    路由

    from django.conf.urls import url, include
    from web.views.s1_api import TestView
     
    urlpatterns = [
        url(r'^test/', TestView.as_view()),
    ]

    视图

    from rest_framework.views import APIView
    from rest_framework.response import Response
     
     
    class TestView(APIView):
        def dispatch(self, request, *args, **kwargs):
            """
            请求到来之后,都要执行dispatch方法,dispatch方法根据请求方式不同触发 get/post/put等方法
             
            注意:APIView中的dispatch方法有好多好多的功能
            """
            return super().dispatch(request, *args, **kwargs)
     
        def get(self, request, *args, **kwargs):
            return Response('GET请求,响应内容')
     
        def post(self, request, *args, **kwargs):
            return Response('POST请求,响应内容')
     
        def put(self, request, *args, **kwargs):
            return Response('PUT请求,响应内容')

    上述就是使用Django REST framework框架搭建API的基本流程,重要的功能是在APIView的dispatch中触发。

  • 相关阅读:
    转:【实用教程】阿里云服务器的配置和使用
    C# 定制错误页面
    C# Session进程外存储
    NOIP200101数的计算
    周末舞会
    queue 队列
    信息学作文
    求三个数的平均数
    Hello world
    Django-Form组件-forms.Form
  • 原文地址:https://www.cnblogs.com/liwenzhou/p/10252460.html
Copyright © 2020-2023  润新知