zoukankan      html  css  js  c++  java
  • Django REST framework框架介绍和基本使用

    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中触发。

     
  • 相关阅读:
    How to get the IIS root path in other application.
    Web.UI.Controls与页面事件的冲突问题。
    分析在服务器上设置计时器的问题。
    首次感觉我的电脑过时了。。。。。。。。郁闷。
    Google Logos
    2005年的最后一天
    TreeView的几个使用小技
    浅淡反射问题
    The restricted headers are:
    在服务器上用Timer遇到的小问题。。。。
  • 原文地址:https://www.cnblogs.com/PythonMrChu/p/10439840.html
Copyright © 2011-2022 走看看