利用Django實現RESTful API(一)

  RESTful API如今很流行,這裏是它的介紹 理解RESTful架構RESTful API設計指南.按照Django的常規方法固然也能夠實現REST,但有一種更快捷、強大的方法,那就是 Django REST framework.它是python的一個模塊,經過在Django裏面配置就能夠把app的models中的各個表實現RESTful API。下面是實現方法:html

1、安裝配置

pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

再到Django的 settings.py 中的INSTALLED_APPS添加 rest_framework,以下:python

INSTALLED_APPS = (
    ...
    'rest_framework',
)

 在根目錄的 url.py 文件中爲rest_framework框架的 loginlogout 視圖添加url:shell

urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

 

2、建立model和Serializer

建立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',)

而後開始同步到數據庫中:django

./manage.py makemigrations snippets
./manage.py migrate

接下來須要作的就是建立 Serializer 類,相似於 Form。它的做用就是從你傳入的參數中提取出你須要的數據,並把它轉化爲 json 格式(注意,已是字節碼了),同時支持反序列化到model對象。在 snippets 文件夾中添加 serializers.py 並在其添加以下:編程

from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES


class SnippetSerializer(serializers.Serializer):                # 它序列化的方式很相似於Django的forms
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': 'textarea.html'})      # style的設置等同於Django的
    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 instancewidget=widgets.Textarea

 

3、使用Serializer

先使用 ./manage.py shell 進入Django的shell中。操做以下:json

能夠看到 Serializer 的使用如同 Django 的 forms.它的反序列化以下:api

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>

同時,咱們還能夠對 querysets 進行序列化,只需簡單地在設置參數 many=True,以下:restful

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])

 

4、使用 ModelSerializer

ModelSerializer相似於Django的 modelform, 能夠直接關聯到models中的表。以下:

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

 

5、在Django的視圖中使用Serializer

首先,能夠像常規Django視圖的寫法同樣寫,返回序列化的輸出數據。

from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@csrf_exempt
def 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, safe=False)

    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)

也能夠寫一個視圖對應其models中的表,實現對它的刪、改、查。

@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)

添加對應的url, 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),
]

最後還要在根目錄的 url.py 中添加對應的映射。

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

這時,全部的配置已經完成了。接下來就是測試咱們的API

6、測試API

爲了方便咱們可使用 httpie 模塊來測試,啓動Django,再在客戶端輸入 http://127.0.0.1:8000/snippets/,操做以下:

 還能夠進行 put 操做,修改對應的內容

如此簡單。。。。。。。

相關文章
相關標籤/搜索