zoukankan      html  css  js  c++  java
  • RESTful API 和 Django REST framework

    100天 cmdb最后一天
    
    
    #RESTful API
    	- 定义规范 如get就是请求题
    	- 面向资源编程 把网络任何东西都当作资源
    	
    	  #给一个url,根据方法的不同对资源做不同的操作
    	  #返回结果和状态码
    
    	  http://www.baidu.com/order/
    	  method:
    	  	- GET
    	  	- POST
    	  	- PUT
    	  	- DELETE
    
    #Django REST framework
    	为什么使用REST framework
    		1.前后端分离的业务需要搭建API
    		2.基于DJango快速开发REST api
    
    1. pip3 install djangorestframework
        2. 创建app01
        3. setting 中加入
    
                INSTALLED_APPS = [
                
                    'rest_framework'
                ]
    
                REST_FRAMEWORK = {
                    'DEFAULT_PERMISSION_CLASSES': [
                        'rest_framework.permissions.IsAdminUser',
                    ],
                    'PAGE_SIZE': 10
                }
        4. app01/models.py
    
                class Publisher(models.Model):
                name = models.CharField(max_length=32,verbose_name="名称",unique=True)
                address = models.CharField(max_length=128,verbose_name="地址")
    
    
                def __str__(self):
                    return self.name
    
                class Meta:
                    verbose_name = "出版社"
                    verbose_name_plural = verbose_name
    
        5. makemigrations migrate
    
        6. 创建超级用户 admin注册Publisher  增加数据
    
        7. 项目/urls.py
    
                urlpatterns = [
                url(r'^admin/', admin.site.urls),
                url(r'^publishers/', views.publisher_list),
                ]
    
        8. app01/views.py
    
            from django.shortcuts import render
            from django.http import HttpResponse
            # Create your views here.
    
            from app01 import models
    
            def publisher_list(request):
                queryset = models.Publisher.objects.all()
    
    
                ##方式一: 列表里套字典
                # data = []
                # for i in queryset:
                #     p_tmp = {
                #         "name":i.name,
                #         "address":i.address
                #     }
                #     data.append(p_tmp)
    
                ##方式二:
                #缺点 图片的字段无法转换为字典
                data = []
                from django.forms.models import model_to_dict  # model 对象 转换成 字典 方式
                for i in queryset:
                    data.append(model_to_dict(i))
    
    
                #方式三:djangorestframework 自提供
                #需要在app01下创建serializers.py文件
    
                from app01 import serializers
    
                serializer = serializers.PublisherSerializer(queryset,many=True)
    
                import json
                return HttpResponse(json.dumps(data),content_type="application/json")
    
        9. app01/serializers.py
    
            from rest_framework import serializers
            from app01 import models
    
    
            class PublisherSerializer(serializers.ModelSerializer):
                class Meta:
                    model = models.Publisher
                    fields = (
                        "id",
                        "name",
                        "address"
                    )
    
    
    
        9. 浏览器访问
    
    序列化
    序列化
    #urls.py
    
        urlpatterns = [
            url(r'^admin/', admin.site.urls),
            url(r'^publishers/$', views.publisher_list),
            url(r'^publishers/(?P<pk>[0-9]+)$', views.publisher_detail),
        ]
    
    #views.py
    
        from django.shortcuts import render
        from django.http import HttpResponse
        from rest_framework.decorators import api_view
        from app01 import models
        from app01 import serializers
        from rest_framework.response import Response
        from rest_framework import status
    
    
    
        @api_view(['GET', 'POST'])
        def publisher_list(request,format=None):
    
            if request.method == 'GET':
                queryset = models.Publisher.objects.all()
                s = serializers.PublisherSerializer(queryset,many=True)
                return Response(s.data)
            if request.method == "POST":
                #创建出版社
                s = serializers.PublisherSerializer(data=request.data)
                if s.is_valid():
                    s.save()
                    return Response(s.data,status=status.HTTP_201_CREATED)
                else:
                    return Response(s.errors,status=status.HTTP_400_BAD_REQUEST)
    
        @api_view(['GET', 'PUT',"DELETE"])
        def publisher_detail(request,pk,format=None):
            try:
                publisher = models.Publisher.objects.get(pk=pk)
            except models.Publisher.DoesNotExist:
                return Response(status=status.HTTP_404_NOT_FOUND)
    
            if request.method == 'GET':
                s = serializers.PublisherSerializer(publisher)
                return Response(s.data)
    
            elif request.method == 'PUT':
                s = serializers.PublisherSerializer(publisher, data=request.data)
                if s.is_valid():
                    s.save()
                    return Response(s.data)
                return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)
    
            elif request.method == 'DELETE':
                publisher.delete()
                return Response(status=status.HTTP_204_NO_CONTENT)
    
    
    #创建超级用户
    pip3 install httpie
    http -a admin:admin111.. http://127.0.0.1:8000/publishers/
    http -a admin:admin111.. http://127.0.0.1:8000/publishers/1
    http -a admin:admin111.. http://127.0.0.1:8000/publishers/2    
    Requests and Responses 
    #urls.py 
        urlpatterns = [
            url(r'^admin/', admin.site.urls),
            url(r'^publishers/$', views.PublisherList.as_view()),
            url(r'^publishers/(?P<pk>[0-9]+)$', views.PublisherDetail.as_view()),
        ]
      
    
    #views.py
    
        # -*- coding: utf-8 -*-
        from django.http import Http404
        from rest_framework.views import APIView
        from rest_framework.response import Response
        from rest_framework import status
        from app01 import models
        from app01 import serializers
    
        from rest_framework import mixins
        from rest_framework import generics
    
        # Create your views here.
    
    
        # class PublisherList(APIView):
        #     """
        #     列出所有的出版社,或者创建一个新的出版社
        #     """
        #
        #     def get(self, request, format=None):
        #         queryset = models.Publisher.objects.all()  # 查询出所有的出版社
        #
        #         s = serializers.PublisherSerializer(queryset, many=True)
        #         return Response(s.data)
        #
        #     def post(self, request, format=None):
        #         s = serializers.PublisherSerializer(data=request.data)
        #         if s.is_valid():  # 如果数据没问题
        #             s.save()
        #             return Response(s.data, status=status.HTTP_201_CREATED)
        #         return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)
    
    
        # class PublisherList(mixins.ListModelMixin,
        #                     mixins.CreateModelMixin,
        #                     generics.GenericAPIView):
        #
        #     queryset = models.Publisher.objects.all()
        #     serializer_class = serializers.PublisherSerializer
        #
        #     def get(self, request, *args, **kwargs):
        #         return self.list(request, *args, **kwargs)
        #
        #     def post(self, request, *args, **kwargs):
        #         return self.create(request, *args, **kwargs)
    
    
        class PublisherList(generics.ListCreateAPIView):
            queryset = models.Publisher.objects.all()
            serializer_class = serializers.PublisherSerializer
    
        #
        # class PublisherDetail(APIView):
        #     """
        #     具体的出版社,查看,修改,删除视图
        #     """
        #     def get_object(self, pk):
        #         try:
        #             return models.Publisher.objects.get(pk=pk)
        #         except models.Publisher.DoesNotExist:
        #             raise Http404
        #
        #     # 查看具体的出版社信息
        #     def get(self, request, pk, format=None):
        #         publisher = self.get_object(pk)
        #         s = serializers.PublisherSerializer(publisher)
        #         return Response(s.data)
        #
        #     # 修改出版社信息
        #     def put(self, request, pk, format=None):
        #         publisher = self.get_object(pk)
        #         s = serializers.PublisherSerializer(publisher, data=request.data)
        #         if s.is_valid():
        #             s.save()
        #             return Response(s.data)
        #         return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)
        #
        #     # 删除出版社信息
        #     def delete(self, request, pk, format=None):
        #         publisher = self.get_object(pk)
        #         publisher.delete()
        #         return Response(status=status.HTTP_204_NO_CONTENT)
    
    
        # class PublisherDetail(mixins.RetrieveModelMixin,
        #                       mixins.UpdateModelMixin,
        #                       mixins.DestroyModelMixin,
        #                       generics.GenericAPIView):
        #
        #     queryset = models.Publisher.objects.all()
        #     serializer_class = serializers.PublisherSerializer
        #
        #     def get(self, request, *args, **kwargs):
        #         return self.retrieve(request, *args, **kwargs)
        #
        #     def put(self, request, *args, **kwargs):
        #         return self.update(request, *args, **kwargs)
        #
        #     def delete(self, request, *args, **kwargs):
        #         return self.destroy(request, *args, **kwargs)
    
    
        class PublisherDetail(generics.RetrieveUpdateDestroyAPIView):
            queryset = models.Publisher.objects.all()
            serializer_class = serializers.PublisherSerializer  
    class view 三种方式

      

  • 相关阅读:
    mysqlbinlog
    MySQL二进制日志
    Slave I/O: Got fatal error 1236
    Zabbix监控nginx-rtmp status(json版)
    shell命令find
    Zabbix监控mysql performance
    Zabbix监控disk performance
    MySQL复制配置(多主一从)
    数据建立和保持时间
    Source insight 中 标题栏路径显示完整路径的方法
  • 原文地址:https://www.cnblogs.com/golangav/p/7660183.html
Copyright © 2011-2022 走看看