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
随机推荐
- poj1631——树状数组求LIS
题目:http://poj.org/problem?id=1631 求LIS即可,我使用了树状数组. 代码如下: #include<iostream> #include<cstdio ...
- DB2 Error Messages (Sorted by SQLCODE)
DB2 Error Messages (Sorted by SQLCODE) DB2 Error Messages (Sorted by SQLCODE) SQLCODE SQLSTATE Descr ...
- jQuery 验证 Validation
jQuery Validation 目录 简介: Form validation made easy. Validate a simple comment form with inline rules ...
- HDU1540(线段树统计连续长度)
---恢复内容开始--- Tunnel Warfare Time Limit:2000MS Memory Limit:32768KB 64bit IO Format:%I64d &am ...
- 五 akka streams kafka
(转载 https://doc.akka.io/docs/akka-stream-kafka/current/home.html) 一: Akka Streams Kafka, also known ...
- 《Java多线程编程核心技术》读后感(四)
将任意对象作为对象监视器 synchronized同步代码块还支持任意对象,使用格式为synchronized(非this对象) package Second; public class Servic ...
- solr-建立单机版的服务器
回到之前打开的页面,刷新,wenda就出来了: 这个wenda是单机版的.
- json字符串与json对象之间的转换
字符串转对象(strJSON代表json字符串) var obj = eval(strJSON); (运用时候需要除了eval()以外需要json.js包) var obj = strJSON. ...
- UVaLive 3266 Tian Ji -- The Horse Racing (贪心)
题意:田忌赛马,每胜一局就得200,负一局少200,问最多得多少钱. 析:贪心,如果最快的马比齐王的还快,就干掉它,如果最慢的马比齐王的马快,就干掉它,否则用最慢的马去和齐王最快的马比. 代码如下: ...
- Dev Envirenment - Windows 10 && Visual Studio 2019 && OpenCV 4.1.0
当每天用着 C# && Winform && VS 2010 && .Net Framework 4.0 && Halcon & ...