python 之路,Django rest framework 初探
摘自 金角大王 https://www.cnblogs.com/alex3714/articles/7131523.html
Django rest framework介绍
Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
- The Web browsable API is a huge usability win for your developers.
- Authentication policies including packages for OAuth1a and OAuth2.
- Serialization that supports both ORM and non-ORM data sources.
- Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
- Extensive documentation, and great community support.
- Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
安装
Requirements
REST framework requires the following:
- Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
- Django (1.8, 1.9, 1.10, 1.11)
The following packages are optional:
- coreapi (1.32.0+) - Schema generation support.
- Markdown (2.1.0+) - Markdown support for the browsable API.
- django-filter (1.0.1+) - Filtering support.
- django-crispy-forms - Improved HTML display for filtering.
- django-guardian (1.1.1+) - Object level permissions support.
Installation
Install using pip
, including any optional packages you want...
1
2
3
|
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django - filter # Filtering support |
...or clone the project from github.
1
|
git clone git@github.com:encode / django - rest - framework.git |
Add 'rest_framework'
to your INSTALLED_APPS
setting.
1
2
3
4
|
INSTALLED_APPS = ( ... 'rest_framework' , ) |
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py
file.
1
2
3
4
|
urlpatterns = [ ... url(r '^api-auth/' , include( 'rest_framework.urls' , namespace = 'rest_framework' )) ] |
Note that the URL path can be whatever you want, but you must include 'rest_framework.urls'
with the 'rest_framework'
namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
快速上手实例
Let's take a look at a quick example of using REST framework to build a simple model-backed API.
We'll create a read-write API for accessing information on the users of our project.
Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK
. Start off by adding the following to your settings.py
module:
1
2
3
4
5
6
7
|
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' ] } |
Don't forget to make sure you've also added rest_framework
to your INSTALLED_APPS
.
We're ready to create our API now. Here's our project's root urls.py
module:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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' )) ] |
You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.
Django视图中使用rest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
from rest_framework import serializers from assets import models from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response class EventLogSerializer(serializers.ModelSerializer): class Meta: model = models.EventLog fields = ( 'id' , 'user' , 'name' , 'event_type' , 'detail' , 'asset' , 'date' , 'memo' ) @api_view ([ 'GET' , 'POST' ]) def eventlog_list(request): """ List all snippets, or create a new snippet. """ if request.method = = 'GET' : eventlogs = models.EventLog.objects. all () serializer = EventLogSerializer(eventlogs, many = True ) return Response(serializer.data) elif request.method = = 'POST' : print ( "request" ,request.data) serializer = EventLogSerializer(data = request.data) if serializer.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']) @csrf_exempt def eventlog_detail(request, pk): """ Retrieve, update or delete a code eventlog. """ try : eventlog_obj = models.EventLog.objects.get(pk = pk) except models.EventLog.DoesNotExist: return HttpResponse(status = 404 ) if request.method = = 'GET' : serializer = EventLogSerializer(eventlog_obj) return JsonResponse(serializer.data) elif request.method = = 'PUT' : print (request) data = JSONParser().parse(request) serializer = EventLogSerializer(eventlog_obj, data = data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status = 400 ) elif request.method = = 'DELETE' : eventlog_obj.delete() return HttpResponse(status = 204 ) |
更多请看 http://www.django-rest-framework.org/
python 之路,Django rest framework 初探的更多相关文章
- 自学Python之路-django
自学Python之路-django 自学Python之路[第一回]:1.11.2 1.3
- Python之路-(Django进阶一)
Django请求生命周期: 首先,客户端发送请求到服务器的urls库,通过匹配url后面的关键字,去找指定app里面的的view. 然后,app通过判断,拿到数据库数据和html模板文件. 最后,将拿 ...
- python之路 django基础
Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...
- Python之路-(Django(Cookie、分页))
Cookie 分页 1.获取Cookie: request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, sal ...
- Python之路-(Django进阶二)
model: 双下划线: # 获取个数 # # models.Tb1.objects.filter(name='seven').count() # 大于,小于 # # models.Tb1.objec ...
- python之路-----django 自定义cookie签名
1.默认自定义cookie 在使用扩展签名时,会根据settings 配置中的 SIGNING_BACKEND 来运行加密方法,默认使用 django.core.signing.TimestampS ...
- Python之路-(Django(csrf,中间件,缓存,信号,Model操作,Form操作))
csrf 中间件 缓存 信号 Model操作 Form操作 csrf: 用 django 有多久,我跟 csrf 这个概念打交道就有久了. 每次初始化一个项目时都能看到 django.middlewa ...
- Django REST framework+Vue 打造生鲜超市(一)
一.项目介绍 1.1.掌握的技术 Vue + Django Rest Framework 前后端分离技术 彻底玩转restful api 开发流程 Django Rest Framework 的功能实 ...
- 1- vue django restful framework 打造生鲜超市
Vue+Django REST framework实战 使用Python3.6与Django2.0.2(Django-rest-framework)以及前端vue开发的前后端分离的商城网站 项目支持支 ...
- Python之路【第十七篇】:Django【进阶篇 】
Python之路[第十七篇]:Django[进阶篇 ] Model 到目前为止,当我们的程序涉及到数据库相关操作时,我们一般都会这么搞: 创建数据库,设计表结构和字段 使用 MySQLdb 来连接 ...
随机推荐
- win10、win11安装子系统kali linux、图形化界面的安装
1.开启安装Linux子系统需要的扩展 Win+Q搜索功能 勾选需要的扩展,Hyper-V.Windows 虚拟机监控平台.适用于Linux的Windows子系统.虚拟机平台 反正这些有关于虚拟机的全 ...
- Python3程序捕获Ctrl+C终止信号
技术背景 对于一些连续运行或者长时间运行的Python程序而言,如服务器的后端,或者是长时间运行的科学计算程序.当我们涉及到一些中途退出的操作时,比如使用Ctrl+C来退出正在运行的程序.这种场景的出 ...
- AI 影评家:用 Hugging Face 模型打造一个电影评分机器人
本文为社区成员 Jun Chen 为 百姓 AI 和 Hugging Face 联合举办的黑客松所撰写的教程文档,欢迎你阅读今天的第二条推送了解和参加本次黑客松活动.文内含有较多链接,我们不再一一贴出 ...
- golang pprof 监控系列(1) —— go trace 统计原理与使用
golang pprof 监控系列(1) -- go trace 统计原理与使用 服务监控系列文章 服务监控系列视频 关于go tool trace的使用,网上有相当多的资料,但拿我之前初学golan ...
- 数仓如何进行表级控制analyze?
摘要: 介绍如何设置采样大小和表级控制analyze. 本文分享自华为云社区<GaussDB(DWS) 如何表级控制analyze>,作者:leapdb. 一.控制采样大小 [设置全局采样 ...
- 重磅!Apache Hudi联合传智教育推出免费中文视频教程
基础介绍 Apache Hudi(简称:Hudi)使得您能在hadoop兼容的存储之上存储大量数据,同时它还提供两种原语,使得除了经典的批处理之外,还可以在数据湖上进行流处理.这两种原语分别是: Up ...
- 刷爆 LeetCode 周赛 339,贪心 / 排序 / 拓扑排序 / 平衡二叉树
本文已收录到 AndroidFamily,技术和职场问题,请关注公众号 [彭旭锐] 提问. 大家好,我是小彭. 上周末是 LeetCode 第 339 场周赛,你参加了吗?这场周赛覆盖的知识点比较少, ...
- 0002 嵌入式开发带你从小白到大佬系列之——Linux文件系统、常用文件操作命令(一)及用户权限
1.熟悉Linux的文件系统结构 Linux的文件系统结构其实是一个树形的分层组织结构,如下图: Linux系统目录结构及目录路径: 1.1.文件系统层次结构标准 Linux是开源的操作系统,各个Li ...
- CentOS7---部署Tomcat和安装Jpress
总览需求 1. 简述静态网页和动态网页的区别. 2. 简述 Webl.0 和 Web2.0 的区别. 3. 安装tomcat8,配置服务启动脚本,部署jpress应用. 1.简述静态网页和动态网页的区 ...
- Linux进程管理(命令)入门
进程是一个运行中的程序 进程查看 ps 能够查看当前终端下运行的进程 $ ps PID TTY TIME CMD 26305 pts/0 00:00:00 bash 26312 pts/0 00:00 ...