一、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. 关于Android的HAL的一些理解

    之前一直在学习基于Linux内核的一些字符型驱动的编程,对Linux内核驱动也算有了一些基本的了解吧,后来也做过一些基于Linux内核的驱动开发,像基于Android的CC1101高频模块的驱动开发, ...

  2. POJ2182(排队问题)

    Lost Cows Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 10695   Accepted: 6865 Descri ...

  3. css属性学习

    CSS display 属性 display 属性规定元素应该生成的框的类型. none:此元素不会被显示. block:此元素将显示为块级元素,此元素前后会带有换行符. inline默认.此元素会被 ...

  4. CF-822B

    B. Crossword solving time limit per test 1 second memory limit per test 256 megabytes input standard ...

  5. STL::next_permutation();

    next_permutation()可以按字典序生成所给区间的全排列. 在STL中,除了next_permutation()外,还有一个函数prev_permutation(),两者都是用来计算排列组 ...

  6. ge lei zi yuan

    introduction to OJ http://acdream.info/topic/101 ji suan ji he mo ban http://wenku.baidu.com/link?ur ...

  7. ES5.X相关API和技巧汇总

    https://blog.csdn.net/laoyang360/article/details/77412668

  8. 1.14不使用回车键来读取n个字符

    read是一个重要的bash命令,它用于从键盘或标准输入中读取文本.可以使用read以交互的形式读取来自用户的输入,不过read能做的远不止这些.很多编程语言的输入库都是从键盘读取输入,且只有回车键按 ...

  9. (转)深度学习(Deep Learning, DL)的相关资料总结

    from:http://blog.sciencenet.cn/blog-830496-679604.html 深度学习(Deep Learning,DL)的相关资料总结 有人认为DL是人工智能的一场革 ...

  10. [Xcode 实际操作]七、文件与数据-(10)NSkeyedArchiver存储和解析数据,Swift对象的归档和恢复归档

    目录:[Swift]Xcode实际操作 本文将演示如何使用归档的方法,对模型对象进行持久化工作. 在项目名称上点击鼠标右键,弹出右键菜单,选择[New File]新建文件命令, 在弹出的模板选项窗口中 ...