zoukankan      html  css  js  c++  java
  • 8 REST Framework 实现Web API 1

    1 参考博客:

        http://blog.csdn.net/SVALBARDKSY/article/details/50548073

        

    2  准备工作

      1. 环境

    Python: Python 3.5 
    Django: 1.9 
    django-filter: 0.11.0 
    djangorestframework: 3.3.1

     2.准备工作

    安装库
    
    pip install django
    pip install djangorestframework
    pip install django-filter 
    
    
    创建工程 app
    django-admin startproject django_rest_framework_test
    cd django_rest_framework_test/
    
    python manage.py startapp blog

     3.定义Model

    from django.db import models
    class User(models.Model):
        name = models.CharField(max_length=32)
        mail = models.EmailField()

      .admin注册

    from django.contrib import admin
    from blog.models import User
    # Register your models here.
    admin.register(User)

       4. 构建DB

    # 添加程序 blog
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'blog',
    ]

      5.然后同步数据结构,默认使用Sqlite3.

    python manage.py makemigrations
    python manage.py migrate

      6.admi后台

    # 创建管理用户
    python manage.py createsuperuser
       Username (leave blank to use 'kimihiro_n'): dev
       Email address:
       Password:
       Password (again):
       Superuser created successfully.
    
    # 启动服务器
    python manage.py runserver

        

    3  使用Djagno REST Framework

       1.添加APP REST Framework

    #django_rest_framework_test/settings.py
    
    INSTALLED_APPS = (
        ...
        'blog',
        'rest_framework',
    )

      2.生成REST

      生成REST API最少需要定义下面3个。 

    • - Serializer 
    • - ViewSet 
    • - URL pattern 

      简单来说,Serializer是将「Model序列化」,ViewSet是API的应答器,URL Pattern定义了URL的路由。

      2.1定义Serialzier

      需要继承serializers.ModelSerializer, fields为API想要得到的字段。

    #blog/serializer.py
    
    # coding: utf-8
    from rest_framework import serializers
    from .models import User, Entry
    
    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = ('name', 'mail')

        

       2.2定义ViewSet

      queryset设置为Model的queryset,serializer_class设置为刚才定义的serializer。

    #blog/views.py
    
    # coding: utf-8
    
    import django_filters
    from rest_framework import viewsets, filters
    
    from .models import User, Entry
    from .serializer import UserSerializer, EntrySerializer
    
    class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

        2.3定义URL pattern

    #django_rest_framework_test/urls.py
    
    
    # coding: utf-8
    
    from django.conf.urls import url, include
    from django.contrib import admin
    
    from blog.urls import router as blog_router
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        #include blog.urls
        url(r'^api/', include(blog_router.urls)),
    ]
    #blog/urls.py
    
    
    # coding: utf-8
    
    from rest_framework import routers
    from .views import UserViewSet, EntryViewSet
    
    router = routers.DefaultRouter()
    router.register(r'users', UserViewSet)
    router.register(r'entries', EntryViewSet)

    4测试API

    python manage.py runserver

    5. 未完成

    自定义API
    
    真正运用的时候,可能需要对抽选进行过滤。另外比如
    
    将关系表数据同时获取
    
    例如下面的数据
    
    {
       "title": "Hello, Django REST API!!",
       "body": "<script>alert("hello");</script>",
       "created_at": "2015-12-09T05:59:46.200277Z",
       "status": "draft",
       "author": 1
    }
    1
    2
    3
    4
    5
    6
    7
    返回的是author的ID。如果这样下次还要通过 /api/users/1再次请求User的数据。这样效率并不好,现在我们想获得下面的数据。
    
    {
       "title": "Hello, Django REST API!!",
       "body": "<script>alert("hello");</script>",
       "created_at": "2015-12-09T05:59:46.200277Z",
       "status": "draft",
       "author": {
           "name": "Alice",
           "mail": "alice@example.com"
       }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    在Serializer里把author的部分,再次定义一下。
    
    blog/serializer.py
    …
    class EntrySerializer(serializers.ModelSerializer):
        # author的serializer
        author = UserSerializer()
    
        class Meta:
            model = Entry
            fields = ('title', 'body', 'created_at', 'status', 'author')
    1
    2
    3
    4
    5
    6
    7
    8
    9
    EntrySerializer 重新定义author,这样获取的时候会同时获得User信息。 
    其他的自定义方法请参照 http://www.django-rest-framework.org/api-guide/serializers/
    
    分页
    
    现在获取数据都是全件获取,数据量非常大的时候,需要对数量进行限制。
    
    django_rest_framework_test/settings.py
    REST_FRAMEWORK = {
        'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
        'PAGE_SIZE': 2
    }
    1
    2
    3
    4
    5
    设置需要全局设置。在配置文件里,定义REST_FRAMEWORK,设置DEFAULT_PAGINATION_CLASS和PAGE_SIZE。 
    这样API会出现offset(开始位置)和limit(限制件数, 
    default=PAGE_SIZE)等参数。
    
    {
        "count": 4,
        "next": "http://localhost:8000/api/entries/?limit=2&offset=2",
        "previous": null,
        "results": [
            {
                "id": 1,
                "title": "Hello, Django REST Framework!!",
                "body": "Hello!",
                "created_at": "2015-12-12T11:55:22.310203Z",
                "status": "draft",
                "author": 1
            },
            {
                "id": 2,
                "title": "The Zen of Python",
                "body": "The Zen of Python, by Tim Peters
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated.
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!",
                "created_at": "2015-12-12T11:56:32.854278Z",
                "status": "draft",
                "author": 2
            }
        ]
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    next,previous都会带有URL,非常的方便。 
    其他方式,参照 http://www.django-rest-framework.org/api-guide/pagination/
    
    筛选
    
    如果想通过author来筛选Entry时。
    
    django_rest_framework_test/settings.py
    REST_FRAMEWORK = {
        'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
    }
    1
    2
    3
    4
    在配置文件里添加DEFAULT_FILTER_BACKENDS。和分页所设置的是同一个字典。
    
    class EntryViewSet(viewsets.ModelViewSet):
        queryset = Entry.objects.all()
        serializer_class = EntrySerializer
        filter_fields = ('author', 'status')
    1
    2
    3
    4
    然后在ViewSet里设置filter_fields。这样就可以通过author和status来筛选。 
    API后面为?author=1,就会抽选User id=1的blog。?status=public会抽选已经公开的Blog 
    其他筛选方法参照 http://www.django-rest-framework.org/api-guide/filtering/
    
    参考URL
    
    http://qiita.com/kimihiro_n/items/86e0a9e619720e57ecd8 
    http://www.django-rest-framework.org/ 
    http://www.slideshare.net/unsolublesugar/res-tful 
    http://qiita.com/KojiOhki/items/5be98eeae72dca2260bc 
    http://racchai.hatenablog.com/entry/2016/04/12/Django_REST_framework_%E8%B6%85%E5%85%A5%E9%96%80
  • 相关阅读:
    第12章 Swing编程
    第11章 AWT编程
    第10章 异常处理
    第9章 泛型
    Java 实例
    Spring 框架 (持续完善中)
    Java 程序员必备的5个框架 (持续完善中)
    IDEA 中建立Java项目步骤
    Java 实例
    Java 实例
  • 原文地址:https://www.cnblogs.com/venicid/p/8228220.html
Copyright © 2011-2022 走看看