一、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. CF 438 E & bzoj 3625 小朋友和二叉树 —— 多项式开方

    题目:http://codeforces.com/contest/438/problem/E https://www.lydsy.com/JudgeOnline/problem.php?id=3625 ...

  2. Adobe Flash Player 27 on Fedora 27/26, CentOS/RHEL 7.4/6.9

    This is guide, howto install Adobe Flash Player Plugin version 27 (32-bit and 64-bit) with YUM/DNF o ...

  3. 人工智能实践:linux 和 python 基础简介

    linux下的目录 绝对路径:是以根目录(" / ")为起点的完整路径,以你所要到的目录为终点. 相对路径:是你当前的目录(" .")为起点的路径,以你所要到的 ...

  4. Advanced R之词汇表

    转载请注明出处:http://www.cnblogs.com/lizichao/p/4800513.html 词汇表 想要玩得转R,重要的一点是有一个好的工作词汇表.以下是我认为的一个好的词汇表.你不 ...

  5. Polygon

    用当前的笔绘制一个由两个或多个点(顶点)连接的多边形. BOOL Polygon( LPPOINT lpPoints, int nCount ); lpPoints 指向一个指定多边形顶点的点.数组中 ...

  6. STM in Clojure

    Transactional memory in Clojure is implemented using Multiversion Concurrency Control protocol http: ...

  7. QDUOJ 炸老师与他的女朋友们 bfs+状压

    炸老师与他的女朋友们 Description qdu最帅的炸老师今天又要抽空去找他的女朋友们了,但是考虑到他的好gay友ycb仍是个单身狗,炸老师作为基友不希望打击他.所以他在找女朋友们的路途中必须要 ...

  8. winform防止界面卡死的三种方法

    在编程过程中经常会遇到耗时操作,这个时候如果不采取一些必要的异步操作,就会导致界面的卡死,这里以winform为例子,介绍三种方法防止界面卡死,对这几个方法稍加修改同样适用于wpf,silverlig ...

  9. 51nod 1562 玻璃切割

      1562 玻璃切割 http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1562 题目来源: CodeForces 基准时间 ...

  10. IT兄弟连 JavaWeb教程 AJAX中参数传递问题

    使用Ajax发送GET请求并需要传递参数时,直接在URL地址后拼接参数,格式如下: xhr.open('get','请求路径?参数名1=参数值1&参数名2=参数值2...',true); 使用 ...