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.

上面是两种默认的认证方式(SessionAuthenticationBasicAuthentication),还有 TokenAuthentication

通过以上,未授权认证的用户只能查看,只有授权认证的用户才可以进行创建,删除,更新操作。

django-rest-framework 使用例子的更多相关文章

  1. 利用 Django REST framework 编写 RESTful API

    利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...

  2. 用Django Rest Framework和AngularJS开始你的项目

    Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...

  3. Django REST FrameWork中文教程2:请求和响应

    从这一点开始,我们将真正开始覆盖REST框架的核心.我们来介绍几个基本的构建块. 请求对象REST框架引入了Request扩展常规的对象HttpRequest,并提供更灵活的请求解析.Request对 ...

  4. Django REST framework反向生成url

    Django REST framework是一个基于Django的框架,REST framework又是怎么反向生成url的呢?? 在前面的例子中,知道在REST framework中有6种版本控制的 ...

  5. Django rest framework源码分析(1)----认证

    目录 Django rest framework(1)----认证 Django rest framework(2)----权限 Django rest framework(3)----节流 Djan ...

  6. django rest framework serializers

    django rest framework serializers序列化   serializers是将复杂的数据结构变成json或者xml这个格式的 serializers有以下几个作用:- 将qu ...

  7. Django Rest framework基础使用之 serializer

    rest-framework文档地址:http://www.django-rest-framework.org/ Django Rest framework是一个非常强大且灵活的工具包,用于构建web ...

  8. Python3+PyCharm+Django+Django REST framework开发教程

    一.说明 自己一是想跟上潮流二是习惯于直接干三是没有人可以请教,由于这三点经常搞得要死要活.之前只简单看过没写过Diango,没看过Django REST framework,今天一步到位直接上又撞上 ...

  9. python 全栈开发,Day96(Django REST framework 视图,django logging配置,django-debug-toolbar使用指南)

    昨日内容回顾 1. Serializer(序列化) 1. ORM对应的query_set和ORM对象转换成JSON格式的数据 1. 在序列化类中定义自定义的字段:SerializerMethodFie ...

  10. Django Rest Framework源码剖析(八)-----视图与路由

    一.简介 django rest framework 给我们带来了很多组件,除了认证.权限.序列化...其中一个重要组件就是视图,一般视图是和路由配合使用,这种方式给我们提供了更灵活的使用方法,对于使 ...

随机推荐

  1. MySQL/MariaDB数据库的视图(VIEW)

     MySQL/MariaDB数据库的视图(VIEW) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.视图概述 1>.什么是视图 视图就是一个虚拟的表,保存有实表的查询结果 ...

  2. Unity进阶之:MVC编程思想

    版权声明: 本文原创发布于博客园"优梦创客"的博客空间(网址:http://www.cnblogs.com/raymondking123/)以及微信公众号"优梦创客&qu ...

  3. Windows解决端口被占用问题

    第一种解决方法,以8080端口为例 打开命令行输入 cmd ,输入netstat -ano 会显示所有已经在运行的端口情况.PID为进程id 输入你想要查的正在占用的端口号,netstat -ano ...

  4. 使用gitlab下载代码(附常用命令)

    Git是现在很多人常用的代码管理工具,这里有一些常用的命令详解,本人接触也不是很久,若有错误,请在评论指出,谢谢. 若计算机中没有安装GIT,可自行查找安装教程,十分简便. ①首先,我们需要下载项目, ...

  5. C#启动计算器并设计算器为活动窗口

    启动计算器,并获取焦点 using System; using System.Runtime.InteropServices; namespace ConsoleApplication3 { clas ...

  6. Python 字符串正则处理实例

    #coding:utf-8 ''' Created on 2017��9��6�� @author: li.liu ''' from selenium import webdriver from se ...

  7. Apache Solr < 8.2.0远程命令执行漏洞(CVE-2019-0193)

    介绍:Apache Solr 是一个开源的搜索服务器.Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现. 漏洞原因:此次漏洞出现在Apache Solr的D ...

  8. 阿里巴巴编程规约--digest

    所谓卫语句,如果某个条件极其罕见,就应该单独检查该条件,并在该条件为真时立刻从函数中返回.这样的单独检查常常被称为“卫语句”. 微服务之间将DTO,Req放到一个单独的项目中,相关的项目都依赖这个底层 ...

  9. Expectation Maximization Algorithm

    期望最大化算法EM. 简介 EM算法即期望最大化算法,由Dempster等人在1976年提出[1].这是一种迭代法,用于求解含有隐变量的最大似然估计.最大后验概率估计问题.至于什么是隐变量,在后面会详 ...

  10. mysql adddate()函数

    mysql> ); +---------------------------+ | adddate() | +---------------------------+ | -- | +----- ...