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

 

posted @ 2019-01-10 21:17  Q1mi  阅读(2771)  评论(0编辑  收藏  举报