美文网首页Django学习
Django rest framework学习笔记1

Django rest framework学习笔记1

作者: 00cadc01cbc1 | 来源:发表于2015-12-28 17:37 被阅读3616次

    参考
    Django rest framework官网http://www.django-rest-framework.org/
    httpie工具使用简介http://blog.csdn.net/pzw_0612/article/details/46521965

    一.序列化

    安装

    pip install django
    pip install djangorestframework
    pip install pygments # We'll be using this for the code highlighting
    

    Getting Started

    django-admin startproject turorial   创建turorial项目
    python manage.py snippets            创建snippets  APP
    

    把APP snippets和rest_framework 添加到turorial/settings.py中的INSTALLED_APP

    INSTALLED_APPS = ( 
      ... 'rest_framework', 'snippets',
    )
    

    然后在turorial/urls.py中添加如下代码

    urlpatterns = [
        url(r'^', include('snippets.urls')),
    ]
    

    Creating a model to work with

    在app snippets/models.py

    from django.db import models
    from pygments.lexers import get_all_lexers
    from pygments.styles import get_all_styles
    
    LEXERS = [item for item in get_all_lexers() if item[1]]
    LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
    STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
    
    class Snippet(models.Model): 
      created = models.DateTimeField(auto_now_add=True) 
      title = models.CharField(max_length=100, blank=True, default='') 
      code = models.TextField() 
      linenos = models.BooleanField(default=False) 
      language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) 
      style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) 
      class Meta: 
        ordering = ('created',)
    

    然后创建数据库

    python manage.py makemigrations snippets
    python manage.py migrate
    

    Create a Serializer class创建数列化类

    在snippet文件夹中创建serializers.py, 此处继承的是Serializer类,非常像django中的form, 但是这里必须要实现一个create方法,update方法.
    当然还有一种继承ModelSerializer的方法

    from rest_framework import serializers
    from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
    
    class SnippetSerializer(serializers.Serializer): 
      pk = serializers.IntegerField(read_only=True) 
      title = serializers.CharField(required=False, allow_blank=True, max_length=100) 
      code = serializers.CharField(style={'base_template': 'textarea.html'}) 
      linenos = serializers.BooleanField(required=False) 
      language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python') 
      style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly') 
      def create(self, validated_data): 
        """ 
        Create and return a new `Snippet` instance, given the validated data. 
        """
        return Snippet.objects.create(**validated_data) 
      def update(self, instance, validated_data): 
      """ Update and return an existing `Snippet` instance, given the validated data. """ 
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos) 
        instance.language = validated_data.get('language', instance.language) 
        instance.style = validated_data.get('style', instance.style) 
        instance.save() 
        return instance
    

    Working with Serializers

    在shell中测试上述序列化api

    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser
    
    #Snippet数据库中创建两条数据
    snippet = Snippet(code='foo = "bar"\n')
    snippet.save()
    
    snippet = Snippet(code='print "hello, world"\n')
    snippet.save()
    
    #创建一个序列化的对象
    serializer = SnippetSerializer(snippet)
    serializer.data
    >>>{'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
    
    
    #使用JSONRenderer().render(serializer.data)吧数据渲染成json数据
    content = JSONRenderer().render(serializer.data)
    content
    >>>'{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
    
    
    #反序列化
    
    #吧流数据转化成python数据
    from django.utils.six import BytesIO
    
    stream = BytesIO(content)
    data = JSONParser().parse(stream)
    
    #把数据转化成实例
    serializer = SnippetSerializer(data=data)
    serializer.is_valid()
    # True
    serializer.validated_data
    # OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
    serializer.save()
    # <Snippet: Snippet object>
    

    Using ModelSerializer

    序列化中的modelserializerf非常像django form表单中涉及到的ModelForm, 上述继承serializers.Serializer的代码可以改成

    class SnippetSerializer(serializers.ModelSerializer): 
      class Meta: 
        model = Snippet 
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
    

    非常简洁,优雅 有没有

    Writing regular Django views using our Serializer

    使用serializers

    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exemptfrom rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    
    class JSONResponse(HttpResponse): 
    """ An HttpResponse that renders its content into JSON. """ 
    def __init__(self, data, **kwargs):
      content = JSONRenderer().render(data) 
      kwargs['content_type'] = 'application/json' 
      super(JSONResponse, self).__init__(content, **kwargs)
    
    @csrf_exemptdef 
    snippet_list(request): 
    """ List all code snippets, or create a new snippet. """ 
      if request.method == 'GET': 
        snippets = Snippet.objects.all() 
        serializer = SnippetSerializer(snippets, many=True)
        return JSONResponse(serializer.data) 
      elif request.method == 'POST': 
        data = JSONParser().parse(request) 
        serializer = SnippetSerializer(data=data) 
        if serializer.is_valid(): 
          serializer.save() 
          return JSONResponse(serializer.data, status=201) 
        return JSONResponse(serializer.errors, status=400)
    
    @csrf_exempt
    def snippet_detail(request, pk):
    """ Retrieve, update or delete a code snippet. """ 
    try: 
      snippet = Snippet.objects.get(pk=pk) 
    except Snippet.DoesNotExist: 
      return HttpResponse(status=404) 
    if request.method == 'GET': 
      serializer = SnippetSerializer(snippet) 
      return JSONResponse(serializer.data) 
    elif request.method == 'PUT': 
      data = JSONParser().parse(request) 
      serializer = SnippetSerializer(snippet, data=data) 
      if serializer.is_valid(): 
        serializer.save() 
        return JSONResponse(serializer.data) 
      return JSONResponse(serializer.errors, status=400) 
    elif request.method == 'DELETE': 
      snippet.delete() 
      return HttpResponse(status=204)
    

    最后在snippets/urls.py中添加

    from django.conf.urls import url
    from snippets import views
    
    urlpatterns = [ 
      url(r'^snippets/$', views.snippet_list), 
      url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
    ]
    

    使用httpie测试api

    pip install httpie
    
    http http://127.0.0.1:8000/snippets/
    http http://127.0.0.1:8000/snippets/2/
    

    相关文章

      网友评论

        本文标题:Django rest framework学习笔记1

        本文链接:https://www.haomeiwen.com/subject/riobhttx.html