【Django】Django-REST-Framework

 

【创建简单的API】

 

1. cmd.exe

>django-admin startproject django_rest
>cd django_rest
\django_rest>python3 manage.py startapp api

2. setting.py 加应用 

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

# 在文件末尾添加
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'PAGE_SIZE': 10
}

 

 

3. 数据库迁移

① models.py 拷贝

② guest工程__init__.py  拷贝

③ setting.py 的数据库配置

④ 

python3 manage.py makemigrations api

python3 manage.py migrate

 

4. 创建超级管理员账号

cmd.exe

\django_rest>python3 manage.py createsuperuser
Username (leave blank to use 'fnngj'): admin_rest
Email address: admin@mail.com
Password:admin123456
Password (again):admin123456
Superuser created successfully

 

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')

【备注】值得注意的是, 这里使用的是 HyperlinkedModelSerializer, 你可以使用主键或者其他关系, 但使用
HyperlinkedModelSerializer 是一个好的 RESTful 设计


6. 创建视图 .../api/views.py

7. URLs
打开.../django_rest/urls.py 文件, 添加路径的路由

8. 启动服务
...\django_rest>python3 manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
November 21, 2016 - 21:50:18
Django version 1.10.3, using settings 'django_rest.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
通过浏览器打开: http://127.0.0.1:8000/


【添加接口】

1. 点击页面右上角“Log in” 登录系统, 账号为刚刚创建的超级管理员帐号登录




点击: http://127.0.0.1:8000/groups/ 链接, 添加用户组。 图 13.4。 添加“test” 组和“developer” 组。
点击: http://127.0.0.1:8000/users/链接, 添加用户。 图 13.5。 添加用户“tom” 和“jack” 。






2. 练习写测试接口
test.py

import unittest
import requests

class UserTest(unittest.TestCase):
'''用户查询测试'''

def setUp(self):
self.base_url = 'http://127.0.0.1:8000/users'

def test_user1(self):
'''test user 1'''
r = requests.get(self.base_url + '/1/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'admin')
self.assertEqual(result['email'],'admin@mail.com')

def test_user2(self):
'''test user 2'''
r = requests.get(self.base_url + '/2/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'admin_rest')
self.assertEqual(result['email'],'admin_rest@mail.com')

def test_user3(self):
r = requests.get(self.base_url + '/3/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'jack')
self.assertEqual(result['email'],'jack@mail.com')

class GroupsTest(unittest.TestCase):
'''用户组查询测试'''
def setUp(self):
self.base_url = 'http://127.0.0.1:8000/groups'

def test_groups1(self):
r = requests.get(self.base_url + '/1/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['name'],'test')

def test_groups2(self):
r = requests.get(self.base_url + '/2/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['name'],'developer')



if __name__ == '__main__':
unittest.main()


3. models.py 复制 guest项目的
4. 数据迁移,参考上方对应的
5. 添加发布会数据序列化, 打开.../api/serializers.py 文件, 添加
……
from api.models import Event, Guest
……
class EventSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Event
fields = ('url','name','address','start_time','limit','status')
class GuestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Guest
fields = ('url','realname','phone','email','sign','event')
6. 打开.../api/views.py 视图文件, 定义发布会视图类。

from api.serializers import EventSerializer,GuestSerializer
from api.models import Event,Guest

# ViewSets define the view behavior.
class EventViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows events to be viewd or edited.
'''
queryset = Event.objects.all()
serialize_class = EventSerializer


class GuestViewSet(viewsets.ModelViewSet):
'''
API endpoint that allows guests to be viewed or edited
'''
queryset = Guest.objects.all()
serializer_class = GuestSerializer


7. 打开.../django_rest/urls.py 文件, 添加 URL 配置

……
#Routers provide an easy way of automatically determining the URL conf.
……
router.register(r'event', views.EventViewSet)
router.register(r'guest', views.GuestViewSet)
……

启动项目, 使用浏览器打开: http://127.0.0.1:8000/







【代码】
环境开户接口
api/serializers.py

from django.contrib.auth.models import User,Group
from rest_framework import serializers
from api.models import Event,Guest

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

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

class GuestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Event
fields = ('url','name','address','start_time','limit','status')


class EventSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Guest
fields = ('url','realname','phone','email','sign','event')





url.py
from django.conf.urls import url,include
from django.contrib import admin
from rest_framework import routers
from api import views

#Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users',views.UserViewSet)
router.register(r'groups',views.GroupViewSet)

router.register(r'event',views.EventViewSet)
router.register(r'guest',views.GuestViewSet)


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


]
#【备注】因为我们使用的是 viewset, 所以我们可以使用 routers 类自动生成 URL conf



tests.py


import unittest
import requests

class UserTest(unittest.TestCase):
'''用户查询测试'''

def setUp(self):
self.base_url = 'http://127.0.0.1:8000/users'

def test_user1(self):
'''test user 1'''
r = requests.get(self.base_url + '/1/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'admin')
self.assertEqual(result['email'],'admin@mail.com')

def test_user2(self):
'''test user 2'''
r = requests.get(self.base_url + '/2/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'admin_rest')
self.assertEqual(result['email'],'admin_rest@mail.com')

def test_user3(self):
r = requests.get(self.base_url + '/3/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['username'],'jack')
self.assertEqual(result['email'],'jack@mail.com')

class GroupsTest(unittest.TestCase):
'''用户组查询测试'''
def setUp(self):
self.base_url = 'http://127.0.0.1:8000/groups'

def test_groups1(self):
r = requests.get(self.base_url + '/1/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['name'],'test')

def test_groups2(self):
r = requests.get(self.base_url + '/2/',auth=('admin_rest','admin123456'))
result = r.json()
self.assertEqual(result['name'],'developer')



if __name__ == '__main__':
unittest.main()
















































 

 

 



 

 

 

posted @ 2017-12-01 14:21  素人渔芙2017  阅读(391)  评论(0编辑  收藏  举报