django-rest-framework 使用例子
Start Your API
创建项目
startproject rest_api
创建APP
startapp task
配置 rest_api/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'task',
)
配置 rest_api/urls.py
# -*- coding:utf-8 -*-
from django.conf.urls import url, include
urlpatterns = [
url(r'^api/', include('task.urls')),
]
创建模型 task/models.py
# -*- coding:utf-8 -*-
from django.db import models
class Task(models.Model):
title = models.CharField('标题', max_length=100)
description = models.TextField('描述')
completed = models.BooleanField('是否完成', default=False)
create_date = models.DateTimeField('创建时间', auto_now_add=True)
def __unicode__(self):
return self.title
序列化 task/serializers.py
# -*- coding:utf-8 -*-
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'description', 'completed', 'create_date')
视图 task/views.py
# -*- coding:utf-8 -*-
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import generics
from .models import Task
from .serializers import TaskSerializer
# 第一种方式:APIView
class TaskList(APIView):
def get(self, request, format=None):
tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# 第二种方式:通用视图 ListCreateAPIView
class TaskListCreate(generics.ListCreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer
# 第三种方式:装饰器 api_view
@api_view(['GET', 'POST'])
def task_list(request):
'''
List all tasks, or create a new task.
'''
if request.method == 'GET':
tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = TaskSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def task_detail(request, pk):
try:
task = Task.objects.get(pk=pk)
except Task.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = TaskSerializer(task)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = TaskSerializer(task, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
task.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
路由 task/urls.py
# -*- coding:utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^tasks/$', views.task_list, name='task_list'),
# url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
# url(r'^tasks/$', views.TaskListCreate.as_view(), name='task_list'),
url(r'^tasks/(?P<pk>[0-9]+)$', views.task_detail, name='task_detail'),
]
Command Line
curl http://localhost:8000/api/tasks/
curl -X POST http://localhost:8000/api/tasks/ -d "title=hello world&description=a whole new world"
curl -X PUT http://localhost:8000/api/tasks/1 -d "title=hello world&description=be nice"
curl -X DELETE http://localhost:8000/api/tasks/1
Permissions & Authentication
创建项目
startproject rest_api
创建 APP
startapp task
配置 rest_api/settings.py
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'task',
)
配置 rest_api/urls.py
# -*- coding:utf-8 -*-
from django.conf.urls import url, include
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include('task.urls')),
]
创建模型 task/models.py
# -*- coding:utf-8 -*-
from django.db import models
class Task(models.Model):
owner = models.ForeignKey('auth.User', related_name='tasks')
title = models.CharField('标题', max_length=100)
description = models.TextField('描述')
completed = models.BooleanField('是否完成', default=False)
create_date = models.DateTimeField('创建时间', auto_now_add=True)
def __unicode__(self):
return self.title
序列化 task/serializers.py
# -*- coding:utf-8 -*-
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Task
fields = ('id', 'title', 'description', 'completed', 'owner')
创建 task/permissions.py
# -*- coding:utf-8 -*-
from rest_framework.permissions import IsAuthenticatedOrReadOnly, SAFE_METHODS
class IsOwnerOrReadOnly(IsAuthenticatedOrReadOnly):
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
return obj.owner == request.user
视图 task/views.py
# -*- coding:utf-8 -*-
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from .models import Task
from .serializers import TaskSerializer
from .permissions import IsOwnerOrReadOnly
class TaskMixin(object):
queryset = Task.objects.all()
serializer_class = TaskSerializer
permission_classes = (IsOwnerOrReadOnly,)
class TaskList(TaskMixin, ListCreateAPIView):
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class TaskDetail(TaskMixin, RetrieveUpdateDestroyAPIView):
pass
路由 task/urls.py
# -*- coding:utf-8 -*-
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^tasks/$', views.TaskList.as_view(), name='task_list'),
url(r'^tasks/(?P<pk>[0-9]+)$', views.TaskDetail.as_view(), name='task_detail'),
]
Command Line
curl http://localhost:8000/api/tasks/
curl -X POST http://localhost:8000/api/tasks/ -d "title=basic&description=BasicAuthentication" -u admin:password
curl -X PUT http://localhost:8000/api/tasks/1 -d "title=basic&description=BasicAuthentication&completed=True" -u admin:password
curl -X DELETE http://localhost:8000/api/tasks/1 -u admin:password
curl -X POST http://localhost:8000/api/tasks/ -H "X-CSRFToken: token" --cookie "sessionid=session; csrftoken=token" -d "title=session&description=SessionAuthentication"
# X-CSRFToken in headers just need be the same with csrftoken in cookie.
上面是两种默认的认证方式(SessionAuthentication
和 BasicAuthentication
),还有 TokenAuthentication
。
通过以上,未授权认证的用户只能查看,只有授权认证的用户才可以进行创建,删除,更新操作。
django-rest-framework 使用例子的更多相关文章
- 利用 Django REST framework 编写 RESTful API
利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...
- 用Django Rest Framework和AngularJS开始你的项目
Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...
- Django REST FrameWork中文教程2:请求和响应
从这一点开始,我们将真正开始覆盖REST框架的核心.我们来介绍几个基本的构建块. 请求对象REST框架引入了Request扩展常规的对象HttpRequest,并提供更灵活的请求解析.Request对 ...
- Django REST framework反向生成url
Django REST framework是一个基于Django的框架,REST framework又是怎么反向生成url的呢?? 在前面的例子中,知道在REST framework中有6种版本控制的 ...
- Django rest framework源码分析(1)----认证
目录 Django rest framework(1)----认证 Django rest framework(2)----权限 Django rest framework(3)----节流 Djan ...
- django rest framework serializers
django rest framework serializers序列化 serializers是将复杂的数据结构变成json或者xml这个格式的 serializers有以下几个作用:- 将qu ...
- Django Rest framework基础使用之 serializer
rest-framework文档地址:http://www.django-rest-framework.org/ Django Rest framework是一个非常强大且灵活的工具包,用于构建web ...
- Python3+PyCharm+Django+Django REST framework开发教程
一.说明 自己一是想跟上潮流二是习惯于直接干三是没有人可以请教,由于这三点经常搞得要死要活.之前只简单看过没写过Diango,没看过Django REST framework,今天一步到位直接上又撞上 ...
- python 全栈开发,Day96(Django REST framework 视图,django logging配置,django-debug-toolbar使用指南)
昨日内容回顾 1. Serializer(序列化) 1. ORM对应的query_set和ORM对象转换成JSON格式的数据 1. 在序列化类中定义自定义的字段:SerializerMethodFie ...
- Django Rest Framework源码剖析(八)-----视图与路由
一.简介 django rest framework 给我们带来了很多组件,除了认证.权限.序列化...其中一个重要组件就是视图,一般视图是和路由配合使用,这种方式给我们提供了更灵活的使用方法,对于使 ...
随机推荐
- Codeforces F. Vus the Cossack and Numbers(贪心)
题目描述: D. Vus the Cossack and Numbers Vus the Cossack has nn real numbers aiai. It is known that the ...
- 烦人的警告 Deprecated: convertStrings was not specified when starting the JVM
python 调用java代码: Deprecated: convertStrings was not specified when starting the JVM. The default beh ...
- Codechef:Fibonacci Number/FN——求通项+二次剩余+bsgs
题意 定义 $F_n$ 为 $$F_n = \left\{\begin{matrix}0, n=0\\ 1, n=1 \\F_{n-1} + F_{n-2}, n > 1\end{matrix} ...
- 《OKR工作法》–让所有人承担自己的职责
<OKR工作法>中提到了一个创业故事,TeaBee,创业的目标是让喜欢喝茶的人喝到好茶. 创业初期作为首席执行官的汉娜和作为总裁的杰克就在将茶叶提供给餐厅还是餐厅供应商上产生了分歧,随后他 ...
- vlang 试用
vlang 是最近出来的一门编程语言,集成了rust,golang, 等语言的特性,轻量.简洁.编译 快速,详细的比价参数可以参考官方文档 安装 目前尽管官方提供了linux以及mac 的二进制文件, ...
- 【csp模拟赛4】基站建设 (station.cpp)
[题目描述] 小 Z 的爸爸是一位通信工程师,他所在的通信公司最近接到了一个新的通 信工程建设任务,他们需要在 C 城建设一批新的基站. C 城的城市规划做得非常好,整个城市被规整地划分为 8 行 8 ...
- 计蒜客 39270.Angel's Journey-简单的计算几何 ((The 2019 ACM-ICPC China Shannxi Provincial Programming Contest C.) 2019ICPC西安邀请赛现场赛重现赛
Angel's Journey “Miyane!” This day Hana asks Miyako for help again. Hana plays the part of angel on ...
- SP19997 MOON2 - Moon Safari (Hard) 【数论,多项式】
题目描述:求 \[ \sum_{i=1}^ni^kr^i \] 对某个质数取模.\(T\)组数据. 数据范围:\(n,r\le 10^{18},\sum k\le 2.56\times 10^6\) ...
- 计蒜客——Nise-Anti-AK Problem
Nise-Anti-AK Problem #include<iostream> using namespace std; int b[1000]; int main() { ios::sy ...
- python 得到列表的第二大的元素
code #coding=utf- l=[,,,,,,] max1=l[] max2=l[] if(max1>max2): pass else: max1,max2=max2,max1 :]: ...