Django Rest framework

Quickstart

创建项目

pip install django
pip install djangorestframework
django-admin.py startproject tutorial .  # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart

同步数据库

python manage.py migrate
python manage.py createsuperuser

序列化

vim tutorial/quickstart/serializers.py
-----------------------------------------------------
from django.contrib.auth.models import User, Group
from rest_framework import serializers


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


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

视图

vim tutorial/quickstart/views.py
---------------------------------------
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

URLs

vim tutorial/urls.py
------------------------
from django.conf.urls import url, include
from rest_framework import routers
from quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

设置

vim tutorial/settings.py
---------------------------------
INSTALLED_APPS = (
    ...
    'rest_framework',
)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAdminUser',
    ],
    'PAGE_SIZE': 10
}
ALLOWED_HOSTS = [u'192.168.1.50']
LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

测试接口

开启

python manage.py runserver 192.168.1.50:8000

测试1(需要已安装http工具)

[root@centos7 ~]# http -a django:django http://192.168.1.50:8000/users/
HTTP/1.0 200 OK
Allow: GET, POST, OPTIONS
Content-Length: 152
Content-Type: application/json
Date: Wed, 10 May 2017 03:24:00 GMT
Server: WSGIServer/0.1 Python/2.7.5
Vary: Accept, Cookie
X-Frame-Options: SAMEORIGIN

{
    "count": 1, 
    "next": null, 
    "previous": null, 
    "results": [
        {
            "email": "[email protected]", 
            "groups": [], 
            "url": "http://192.168.1.50:8000/users/1/", 
            "username": "django"
        }
    ]
}

测试2

bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "[email protected]",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "[email protected]",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}

测试3

http://192.168.1.50:8000/users/

![24.png](http://upload-images.jianshu.io/upload_images/5885762-22c043ca5df92ba7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

你可能感兴趣的:(Django Rest framework)