一、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分析的更多相关文章

  1. Django 之restfromwork 源码---APIView 分析

    Django 之 djangorestframework的APIView分析 APIView 类中的as_view() 方法 首先 我们从视图函数入手,在urls.py 中的 URLconfig中添加 ...

  2. Linux安装程序Anaconda分析(续)

    本来想写篇关于Anaconda的文章,但看到这里写的这么详细,转,原文在这里:Linux安装程序Anaconda分析(续) (1) disptach.py: 下面我们看一下Dispatcher类的主要 ...

  3. drf安装与APIView初步分析

    drf安装 1. pip install djangorestframework 2. 在settings文件中注册app : INSTALLED_APPS = [..., 'rest_framewo ...

  4. Linux安装程序Anaconda分析

    1.概述     Anaconda是RedHat.CentOS.Fedora等Linux的安装管理程序.它能够提供文本.图形等安装管理方式,并支持Kickstart等脚本提供自己主动安装的功能.此外, ...

  5. Android应用程序安装过程源代码分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6766010 Android系统在启动的过程中, ...

  6. 安装mysqlsla性能分析工具

    开启mysql慢查询日志 vi /etc/my.cnf slow-query-log = on  #开启MySQL慢查询功能 slow_query_log_file = /data/mysql/127 ...

  7. Apache的安装与AWstats分析系统

    实验拓扑图: 实验要求: 1.  WEB服务器: 使用源码包apache实现.安装完成后,并优化执行路径. 启动服务后,客户端通过http://IP能访问默认的网站. 2.  DNS服务器: 安装DN ...

  8. 《阿里巴巴Java开发手册》扫描插件正式发布--插件安装和使用分析

    "不管做什么,只要坚持下去就会看到不一样!在路上,不卑不亢!" 阿里巴巴于10月14日上午9:00在杭州云栖大会<研发效能峰会>上,正式发布<阿里巴巴Java开发 ...

  9. facebook工具xhprof的安装与使用-分析php执行性能

    下载源码包的网址 http://pecl.php.net/package/xhprof

随机推荐

  1. SQL一次性插入大量数据【转载】

    在SQL Server 中插入一条数据使用Insert语句,但是如果想要批量插入一堆数据的话,循环使用Insert不仅效率低,而且会导致SQL一系统性能问题.下面介绍SQL Server支持的两种批量 ...

  2. JSP+JavaBean+Servlet工作原理实例…

    JSP+JavaBean+Servlet工作原理实例讲解 首先,JavaBean和Servlet虽都是Java程序,但是是完全不同的两个概念.引用mz3226960提出的MVC的概念,即M-model ...

  3. boost编译配置及简单使用

    boost编译配置及简单使用 1.下载 http://www.boost.org/ 2.编译: A.解压 boost_1_55_0.zip 到boost路径 B.运行 bootstrap.bat. 会 ...

  4. MySQL 之 扩展例子

    扩展例子 插入一条记录 INSERT INTO 表名 [(字段1,…,字段n)] VALUES (值1,…,值n) 插入查询的结果 INSERT INTO 表名 (字段1,…,字段n) VALUES ...

  5. 5.zip隐写术

    首先分析pcapng,来得到flag. 先亮出下载地址:http://ctf5.shiyanbar.com/misc/LOL/LOL.pcapng 由于这是.pcapng,需要下载 wireshark ...

  6. Gym - 101889E Enigma(数位填数+记忆化)

    https://cn.vjudge.net/problem/Gym-101889E 1??????????????????????????????? 2 10000000000000000000000 ...

  7. EditText 设置可以输入的字符,过滤不符合接口要求的数据的方法

    1.设置EditText的android:digits 属性, 这种方式可以指出要支持的字符.比如要限制只能输入数字和字母,可以这样android:digits="1234567890ABC ...

  8. 洛谷P2652 同花顺

    P2652 同花顺 题目背景 所谓同花顺,就是指一些扑克牌,它们花色相同,并且数字连续. 题目描述 现在我手里有n张扑克牌,但它们可能并不能凑成同花顺.我现在想知道,最少更换其中的多少张牌,我能让这 ...

  9. Spring Boot Dubbo 构建分布式服务

    概述: 节点角色说明 节点 角色说明 Provider 暴露服务的服务提供方 Consumer 调用远程服务的服务消费方 Registry 服务注册与发现的注册中心 Monitor 统计服务的调用次数 ...

  10. IT兄弟连 Java语法教程 Java语言的其他特性

    Java语言中除了非常重要的跨平台特性外,还有如下几个关键特性: ●  语法简单易学 Java语言的语法简单明了,容易掌握,而且是纯面向对象(OOP)的语言,Java语言的简单性主要体现在以下几个方面 ...