django restframework 快速入门
基本流程
- 建立 Models
- 依靠 Serialiers 将数据库取出的数据 Parse 为 API 的数据(可用于返回给客户端,也可用于浏览器显示)
- ViewSet 是一个 views 的集合,根据客户端的请求(GET、POST等),返回 Serialiers 处理的数据 权限 Premissions 也在这一步做处理
- ViewSet 可在 Routers 进行注册,注册后会显示在 Api Root 页上
在 urls 里注册 ViewSet 生成的 view,指定监听的 url
1 安装
pip install django
pip install djangorestframework
2 创建项目和启动APP
django-admin.py startproject tutorial . # Note the trailing '.' character
cd tutorial
django-admin.py startapp quickstart
使用pycharm的话这些命令都是不用手动去敲的,但是你要会这些知识
3 同步数据库和创建django admin用户
python manage.py migrate
python manage.py createsuperuser --email admin@example.com --username admin
4 序列器
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')
显示超连接,继承serializers.HyperlinkedModelSerializer,model那个表,fields是要序列那些字段
5 views视图
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from tutorial.quickstart.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
6 路由 urls
from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views
# 下面是自动配置urls
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'))
]
7 settings
INSTALLED_APPS = (
...
'rest_framework',
)
启动一下server吧
python manage.py runserver
结果
浏览器访问 http://127.0.0.1:8000/users/