restframework安装及APIView分析
一、restframework的安装
方式一:pip3 install djangorestframework
方式二:pycharm图形化界面安装
方式三:pycharm命令行下安装(装在当前工程所用的解释器下)
二、基于Django实现的API(不带restframework)
FBV
from django.shortcuts import render,HttpResponse # Create your views here.
import json def users(request):
response = {'code':1000,'data':None} #code用来表示状态,比如1000代表成功,1001代表
response['data'] = [
{'name':'haiyan','age':22},
{'name':'haidong','age':10},
{'name':'haixiyu','age':11},
]
return HttpResponse(json.dumps(response)) #返回多条数据 def user(request,pk):
if request.method =='GET':
return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据
elif request.method =='POST':
return HttpResponse(json.dumps({'code':1111})) #返回一条数据
elif request.method =='PUT':
pass
elif request.method =='DELETE':
pass views
CBV
from django.views import View
class UsersView(View):
def get(self,request):
response = {'code':1000,'data':None}
response['data'] = [
{'name': 'haiyan', 'age': 22},
{'name': 'haidong', 'age': 10},
{'name': 'haixiyu', 'age': 11},
]
return HttpResponse(json.dumps(response),stutas=200) class UserView(View):
def get(self,request,pk):
return HttpResponse(json.dumps({'name':'haiyan','age':11})) #返回一条数据
def post(self,request,pk):
return HttpResponse(json.dumps({'code':1111})) #返回一条数据
def put(self,request,pk):
pass
def delete(self,request,pk):
pass views
三、restframework里封装的APIView分析
基于django实现的API许多功能都需要我们自己开发,这时候djangorestframework就给我们提供了方便,直接基于它来返回数据,总之原理都是一样的,就是给一个接口也就是url,让前端的人去请求这个url去获取数据,在页面上显示出来。这样也就达到了前后端分离的效果。
as_view方法
@classmethod
def as_view(cls, **initkwargs):
"""
Store the original class on the view function. This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
"""
if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet):
def force_evaluation():
raise RuntimeError(
'Do not evaluate the `.queryset` attribute directly, '
'as the result will be cached and reused between requests. '
'Use `.all()` or call `.get_queryset()` instead.'
)
cls.queryset._fetch_all = force_evaluation view = super(APIView, cls).as_view(**initkwargs)
view.cls = cls
view.initkwargs = initkwargs # Note: session based authentication is explicitly CSRF validated,
# all other authentication is CSRF exempt.
return csrf_exempt(view) as_view方法
dispatch方法
def dispatch(self, request, *args, **kwargs):
"""
`.dispatch()` is pretty much the same as Django's regular dispatch,
but with extra hooks for startup, finalize, and exception handling.
"""
self.args = args
self.kwargs = kwargs
request = self.initialize_request(request, *args, **kwargs)
self.request = request
self.headers = self.default_response_headers # deprecate? try:
self.initial(request, *args, **kwargs) # Get the appropriate handler method
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc:
response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs)
return self.response dispatch
initialize_request
def initialize_request(self, request, *args, **kwargs):
"""
Returns the initial request object.
"""
parser_context = self.get_parser_context(request) return Request(
request,
parsers=self.get_parsers(),
authenticators=self.get_authenticators(),
negotiator=self.get_content_negotiator(),
parser_context=parser_context
) initialize_request
initial方法(内部调用认证,权限和频率)
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request
neg = self.perform_content_negotiation(request)
request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use.
version, scheme = self.determine_version(request, *args, **kwargs)
request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted
self.perform_authentication(request)
self.check_permissions(request)
self.check_throttles(request) initial方法(内部调用认证,权限和频率)
restframework安装及APIView分析的更多相关文章
- Django 之restfromwork 源码---APIView 分析
Django 之 djangorestframework的APIView分析 APIView 类中的as_view() 方法 首先 我们从视图函数入手,在urls.py 中的 URLconfig中添加 ...
- Linux安装程序Anaconda分析(续)
本来想写篇关于Anaconda的文章,但看到这里写的这么详细,转,原文在这里:Linux安装程序Anaconda分析(续) (1) disptach.py: 下面我们看一下Dispatcher类的主要 ...
- drf安装与APIView初步分析
drf安装 1. pip install djangorestframework 2. 在settings文件中注册app : INSTALLED_APPS = [..., 'rest_framewo ...
- Linux安装程序Anaconda分析
1.概述 Anaconda是RedHat.CentOS.Fedora等Linux的安装管理程序.它能够提供文本.图形等安装管理方式,并支持Kickstart等脚本提供自己主动安装的功能.此外, ...
- Android应用程序安装过程源代码分析
文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6766010 Android系统在启动的过程中, ...
- 安装mysqlsla性能分析工具
开启mysql慢查询日志 vi /etc/my.cnf slow-query-log = on #开启MySQL慢查询功能 slow_query_log_file = /data/mysql/127 ...
- Apache的安装与AWstats分析系统
实验拓扑图: 实验要求: 1. WEB服务器: 使用源码包apache实现.安装完成后,并优化执行路径. 启动服务后,客户端通过http://IP能访问默认的网站. 2. DNS服务器: 安装DN ...
- 《阿里巴巴Java开发手册》扫描插件正式发布--插件安装和使用分析
"不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!" 阿里巴巴于10月14日上午9:00在杭州云栖大会<研发效能峰会>上,正式发布<阿里巴巴Java开发 ...
- facebook工具xhprof的安装与使用-分析php执行性能
下载源码包的网址 http://pecl.php.net/package/xhprof
随机推荐
- SET_Matplotlib
fig.tight_layout() 调整子图间距 legend 图例分开显示
- AtCoder Grand Contest 009 E:Eternal Average
题目传送门:https://agc009.contest.atcoder.jp/tasks/agc009_e 题目翻译 纸上写了\(N\)个\(1\)和\(M\)个\(0\),你每次可以选择\(k\) ...
- Teams Formation
题意: 给定一长度为 n 的整数序列 $a$,将其复制m次,并接成一条链,每相邻K个相同的整数会消除,然后其他的整数继续结成一条链,直到不能消除为止,求问最终剩余多少个整数. 解法: 首先将长度为n的 ...
- 使用BIND安装智能DNS服务器(一)---基本的主从DNS服务器搭建
参考网址:http://www.unixmen.com/dns-server-installation-step-by-step-using-centos-6-3/ DNS(Domain Name S ...
- 虚拟机出现ping DUP
在主机的网络连接里,停用虚拟网卡vmnet1和vmnet8,再启用虚拟网卡vmnet1和vmnet8.
- 2-3 Flutter开发环境与iOS开发环境设置(Mac)
Mac下环境搭建 先不看了 都是Mac下的环境搭建
- # program once 用途 及与 ifndef使用异同
在头文件中用这种写法就是为了该头文件被重复包含时不会出现符合重定义的错误. 效果等同于 #ifndef __xxx__ #define __xxx__ ... #endi ...
- gitHub上传代码
首先进入github官网注册一个帐号 00.png 注册完帐号之后创建一个项目 01.png 设置创建项目的信息 02.png 创建项目完之后复制项目的地址,以供后面下载项目使用 03.png 在桌面 ...
- Sharepoint2013搜索学习笔记之修改搜索拓扑(三)
搜索服务新建好之后可以从管理中心,应用程序管理页面,进入搜索服务的管理页面,进入管理页面之后可以看到当前sharepoint场的搜索拓扑结构. 如果sharepoint场内有多台服务器,需要将搜索组件 ...
- Object Detection(RCNN, SPPNet, Fast RCNN, Faster RCNN, YOLO v1)
RCNN -> SPPNet -> Fast-RCNN -> Faster-RCNN -> FPN YOLO v1-v3 Reference RCNN: Rich featur ...