15.django之Django-Rest-Framework

1.首先安装Django-Rest-Framework

pip3 install djangorestframework
pip3 install markdown Markdown为可视化 API 提供了支持
pip3 install django-filter

2.使用pycharm创建一个工程和一个app

工程名:restful

app名:api

数据库默认使用sqlite3

3.配置rest_framework

打开settings文件		


INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework' #新增
]

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

4.同步数据库

python manage.py makemigrations
python manage.py migrate

5.序列化

在api下面创建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')

6.添加视图

在api的views里添加如下代码
from django.shortcuts import render

# Create your views here.
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from api.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    允许查看和编辑user 的 API endpoint
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    允许查看和编辑group的 API endpoint
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

7.设置url

在restful下面urls

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
	#添加
    url(r'^api/', include('api.urls')),
]


在api下面创建urls
添加

from django.conf.urls import patterns, url, include
from rest_framework import routers
from api 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 browseable API.
urlpatterns = [
        url(r'^', include(router.urls)),
		#验证登录使用
        url(r'auth',include('rest_framework.urls'))
        ]

8.启动访问



posted @ 2016-11-13 12:44  刘耀  阅读(4290)  评论(3编辑  收藏  举报