本节内容
Django rest framework 安装
Django rest framwwork 环境配置
简单举例说明
Django中使用 rest framework
1.1 安装 Django rest framework
建立新的环境 可以忽略
virtualenv env
source env/bin/activate
安装 djangorestframework 模块
pip install django
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
2 Django rest framework 环境配置
1.配置settings文件
在项目配置文件settings的INSTALLED_APPS中添加 ‘rest_framework’
在settings最后一行增加一下内容:允许未认证的用户只读权限
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
3 简单的举例说明
先来看下我Django项目的目录结构
第一步我们需要在 crm_1的 urls下添加 rest framework 的指向信息,这里我们把api的请求指向到app01下的urls.py
urlpatterns = [
url(r'^api/',include('app01.urls') ),
]
在app01的urls.py中写如下内容
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '40kuai'
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'is_staff')
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# 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'))
]
配置了这些之后你就可以启动你的Django项目并且来访问api,
python manage makemigrations
python manage migrate
python manage createsuperuser # 创建第一个用户数据方便在api中查看信息
页面显示
登录后可以查看和编辑数据
下面我们来创建两个有关联关系的表。来看看api怎么显示。
先来创建两个表, 一个角色表。一个菜单表,一个角色可以后多个菜单
from django.db importmodels#Create your models here.
classRole(models.Model):"""角色表"""name= models.CharField(max_length=64,unique=True)
menus= models.ManyToManyField("Menu",blank=True,null=True)def __str__(self):returnself.nameclassMenu(models.Model):"""一级菜单"""name= models.CharField(max_length=64)
url_type_choices= ((0,'absolute'),(1,'relative'))
url_type= models.PositiveIntegerField(choices=url_type_choices,default=1)
url_string= models.CharField(max_length=128)
order= models.SmallIntegerField(default=0)def __str__(self):returnself.nameclassMeta:
unique_together= ("url_string",'url_type')
models.py
在admin.py中注册下, 我们通过Django admin来添加几条数据
from app01 importmodels
admin.site.register(models.Menu)
admin.site.register(models.Role)
admin.py
创建完成后表中的数据
Roles
Menus
下面根据上面实例的配置来先配置Role表,让表Role通过api来显示,并且把各个处理的方法单独分开
先只配置了Role表,来看看效果
在你要显示的表中存在关联关系的时候,需要给关联表也做相应配置
完整的配置 app01目录下的配置
#!/usr/bin/env python#-*- coding:utf-8 -*-
__author__ = '40kuai'
from django.conf.urls importurl, includefrom app01 importrest_routers#Wire up our API using automatic URL routing.#Additionally, we include login URLs for the browsable API.
urlpatterns =[
url(r'^', include(rest_routers.router.urls)),
url(r'^api-auth/', include('rest_framework.urls',namespace='rest_framework'))
]
urls.py
#!/usr/bin/env python#-*- coding:utf-8 -*-
__author__ = '40kuai'
from rest_framework importroutersfrom app01.rest_viewsets import *
"""负责对url进行绑定
类似与Django admin的注册"""router=routers.DefaultRouter()
router.register(r'role', RoleViewSet)
router.register(r'menu', MenuViewSet)
rest_routers.py
#!/usr/bin/env python#-*- coding:utf-8 -*-
__author__ = '40kuai'
from rest_framework importviewsetsfrom app01.rest_serializers import *
from app01 importmodels"""把数据库中的数据取出来,交给序列化进行处理
类似Django中的的视图函数"""
classRoleViewSet(viewsets.ModelViewSet):
queryset=models.Role.objects.all()
serializer_class=RoleSerializerclassMenuViewSet(viewsets.ModelViewSet):
queryset=models.Menu.objects.all()
serializer_class= MenuSerializer
rest_viewsets.py
#!/usr/bin/env python#-*- coding:utf-8 -*-
__author__ = '40kuai'
from rest_framework importserializersfrom app01 importmodels"""序列化要展示的数据"""
classRoleSerializer(serializers.HyperlinkedModelSerializer):classMeta:#depth = 1 # 展示的深度
model =models.Role
fields= ('url','name', 'menus', )classMenuSerializer(serializers.HyperlinkedModelSerializer):classMeta:
model=models.Menu
fields= ('url','name', 'url_type','url_string','order' )
rest_serializers.py
现在页面就可以正常访问了。
显示关联表里的详细信息:
serializers 类的配置的class Meta中添加 depth = 2 来指定 数据查询的深度
serializers.HyperlinkedModelSerializer # 显示对象的url
ModelSerializer # 显示对象的id
4 Django 视图函数和rest framework 结合使用
# 接口新加两条路由信息
url(r'^eventlog_list/', views.eventrole_list),
url(r'^eventlog_detail/(\d+)/', views.eventrole_detail),
from django.shortcuts importrender#Create your views here.
from rest_framework importserializersfrom app01 importmodelsfrom django.http importHttpResponse, JsonResponsefrom django.views.decorators.csrf importcsrf_exemptfrom rest_framework.renderers importJSONRendererfrom rest_framework.parsers importJSONParserfrom rest_framework.decorators importapi_viewfrom rest_framework importstatusfrom rest_framework.response importResponseclassEventRoleSerializer(serializers.ModelSerializer):classMeta:
model=models.Role
fields= ('id','name', 'menus')
@api_view(['GET', 'POST'])defeventrole_list(request):"""List all snippets, or create a new snippet."""
if request.method == 'GET':
eventroles=models.Role.objects.all()
serializer= EventRoleSerializer(eventroles, many=True)returnResponse(serializer.data)elif request.method == 'POST':print("request", request.data)
serializer= EventRoleSerializer(data=request.data)ifserializer.is_valid():
serializer.save()return Response(serializer.data, status=status.HTTP_201_CREATED)return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'POST','PUT','DELETE'])
@csrf_exemptdefeventrole_detail(request, pk):"""Retrieve, update or delete a code eventlog."""
try:
eventrole_obj= models.Role.objects.get(pk=pk)exceptmodels.Role.DoesNotExist:return HttpResponse(status=404)if request.method == 'GET':
serializer=EventRoleSerializer(eventrole_obj)returnJsonResponse(serializer.data)elif request.method == 'PUT':print(request)
data=JSONParser().parse(request)
serializer= EventRoleSerializer(eventrole_obj, data=data)ifserializer.is_valid():
serializer.save()returnJsonResponse(serializer.data)return JsonResponse(serializer.errors, status=400)elif request.method == 'DELETE':
eventrole_obj.delete()return HttpResponse(status=204)
views.py
自己测得玩玩就好, 这只是个入门。