Django-Rest-Framework 入门

  • 时间:
  • 来源:互联网
  • 文章标签:

http://www.django-rest-framework.org/

http://www.weiguda.com/blog/18/

本篇中, 我们会创建一个简单的API, 用来查看和编辑django默认的user和group数据.

1. 设置

我们创建django项目tutorial, 和app quickstart:

    # 创建新Django项目
    django-admin.py startproject tutorial
    cd tutorial

    # 使用virtualenvwrapper创建Virtualenv
    mkvirtualenv env
    workon env

    # 在env中安装Django 和 Django REST framework
    
pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support
# 创建新app python manage.py startapp quickstart

然后根据自己的数据库配置设置数据库:

    # tutorial/settings.py
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'database_name',
            'USER': 'database_user',
            'PASSWORD': 'database_password',
            'HOST': '',
            'PORT': ''
        }
    }
    ...
    INSTALLED_APPS = (
        ...
        'quickstart',
        'rest_framework',
    )

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
        'PAGINATE_BY': 10
    }

最后同步数据库

python manage.py makemigrations
python manage.py migrate

2.序列化 接下来我们创建用于数据序列化的代码

# serializers.py
from django.contrib.auth.models import Group
from .models import User,Rest
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'id', 'username', 'email', 'is_staff')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

class RestSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Rest
        fields = ('url', 'user', 'password')


值得注意的是, 我们使用的是HyperlinkedModelSerializer. 你可以使用主键或者其他关系, 但使用HyperlinkedModelSerializer是一个好的 RESTful 设计.

3. Views

  
#views.py
from django.contrib.auth.models import Group
from rest_framework import routers, serializers, viewsets
from serializers import UserSerializer,GroupSerializer,RestSerializer


# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

class RestViewSet(viewsets.ModelViewSet):
    queryset = Rest.objects.all()
    serializer_class = RestSerializer

在django_rest_framework中, 所有常见的行为都被归到了ViewSets中. 当然我们可以将这些行为分拆出来, 但使用ViewSets, 使view的逻辑更为清楚.

使用queryset和serializer_class代替model变量, 使我们能更加好的控制API行为, 这也是我们推荐的使用方式.

4. URLs

    
from django.conf.urls import url,include
from blog.views import *
# Routers provide an easy way of automatically determining the URL conf.
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'groups', GroupViewSet)
router.register(r'rest', RestViewSet)


urlpatterns = [

    url(r'^$', index, name='index'),
    url(r'^archive/$', archive, name='archive'),
    url(r'^article/$', article, name='article'),
    url(r'^category/$', category, name='category'),
    url(r'^tags/$', tags, name='tags'),
    url(r'^comment/post/$', comment_post, name='comment_post'),

    url(r'^logout$', do_logout, name='logout'),
    url(r'^login', do_login, name='login'),
    url(r'^reg', reg, name='reg'),

    #ajax
    url(r'^data/(?P<id>\d+)/$', data),
    url(r'^update/', update),
    url(r'^senddate/', senddate),

    #rest api
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),

]

因为我们使用的是viewset, 所以我们可以使用route class自动生成url conf.

5. 测试

至此我们的设置完成, 可以测试我们的REST API了, 首先启动django服务器:

    python ./manage.py runserver

我们可以使用postman直接使用浏览器也可以:



原文链接: http://www.weiguda.com/blog/18/



本文链接http://www.taodudu.cc/news/show-647453.html