Django源码分析——response.py

 1 class HttpResponse(HttpResponseBase):
 2     """
 3     An HTTP response class with a string as content.
 4
 5     This content that can be read, appended to or replaced.
 6     """
 7
 8     streaming = False
 9
10     def __init__(self, content=‘‘, *args, **kwargs):
11         super(HttpResponse, self).__init__(*args, **kwargs)
12         # Content is a bytestring. See the `content` property methods.
13         self.content = content
14
15     def serialize(self):
16         """Full HTTP message, including headers, as a bytestring."""
17         return self.serialize_headers() + b‘\r\n\r\n‘ + self.content
18
19     if six.PY3:
20         __bytes__ = serialize
21     else:
22         __str__ = serialize
23
24     def _consume_content(self):
25         # If the response was instantiated with an iterator, when its content
26         # is accessed, the iterator is going be exhausted and the content
27         # loaded in memory. At this point, it‘s better to abandon the original
28         # iterator and save the content for later reuse. This is a temporary
29         # solution. See the comment in __iter__ below for the long term plan.
30         if self._base_content_is_iter:
31             self.content = b‘‘.join(self.make_bytes(e) for e in self._container)
32
33     @property
34     def content(self):
35         self._consume_content()
36         return b‘‘.join(self.make_bytes(e) for e in self._container)
37
38     @content.setter
39     def content(self, value):
40         if hasattr(value, ‘__iter__‘) and not isinstance(value, (bytes, six.string_types)):
41             self._container = value
42             self._base_content_is_iter = True
43             if hasattr(value, ‘close‘):
44                 self._closable_objects.append(value)
45         else:
46             self._container = [value]
47             self._base_content_is_iter = False
48
49     def __iter__(self):
50         # Raise a deprecation warning only if the content wasn‘t consumed yet,
51         # because the response may be intended to be streamed.
52         # Once the deprecation completes, iterators should be consumed upon
53         # assignment rather than upon access. The _consume_content method
54         # should be removed. See #6527.
55         if self._base_content_is_iter:
56             warnings.warn(
57                 ‘Creating streaming responses with `HttpResponse` is ‘
58                 ‘deprecated. Use `StreamingHttpResponse` instead ‘
59                 ‘if you need the streaming behavior.‘,
60                 PendingDeprecationWarning, stacklevel=2)
61         if not hasattr(self, ‘_iterator‘):
62             self._iterator = iter(self._container)
63         return self
64
65     def write(self, content):
66         self._consume_content()
67         self._container.append(content)
68
69     def tell(self):
70         self._consume_content()
71         return len(self.content)

是跟着render来的

from django.http import

时间: 2024-12-08 18:44:43

Django源码分析——response.py的相关文章

Django源码分析——urlresolvers.py

因为看URL,所以跟到了urlresolvers.py regex是正则表达式 view kwargs name 就是那个 name='blog' prefix 1 class RegexURLResolver(LocaleRegexProvider): 2 def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None): 3 LocaleRegexProvider.__ini

Django源码分析——context.py

1 class RequestContext(Context): 2 """ 3 This subclass of template.Context automatically populates itself using 4 the processors defined in TEMPLATE_CONTEXT_PROCESSORS. 5 Additional processors can be specified as a list of callables 6 using

django源码分析

原文网址 https://www.jianshu.com/p/17d78b52c732?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation 环境说明 [x] Python 3.5 [x] Django 1.10.4 创建一个django项目 C:\Users\zhengtong>C:\Python35\Scripts\django-admin.exe st

django源码分析——静态文件staticfiles中间件

本文环境python3.5.2,django1.10.x系列 1.在上一篇文章中已经分析过handler的处理过程,其中load_middleware就是将配置的中间件进行初始化,然后调用相应的设置方法. django框架提供的认证,回话保持,静态文件调试处理等都是通过以中间件的形式来处理. 2.本节就分析一下django框架提供的staticfiles中间件,该中间件分别实现了三个框架的命令,分别为collectstatic,findstatic,runserver. 其中,runserver

Django源码分析之server

乍见 Django内置的server基本包括两部分:django.core.servers和django.core.handlers 相识 servers.basehttp是Django自身提供的一个用于开发测试的server模块,其中提供的WSGIServer.ServerHandler.WSGIRequestHandler其实都是属于WSGI server,django只不过是对python内置的WSGI模块simple_server做的一层包装. handlers package包括bas

Django源码分析之权限系统_擒贼先擒王

乍见 Django内置的权限系统已经很完善了,加上django-guardian提供的功能,基本上能满足大部分的权限需求.暂且不说django-guardian,我们先来看下Django内置的权限系统:django.contrib.auth 包. 相识 一般权限系统分为全局权限和对象权限.Django只提供了一个对象权限的框架,具体实现由第三方库django-gardian完成.我们只看全局权限. 先来看auth包暴露出哪些接口. django.contrib.auth.__init__.py

Django源码分析——shotcuts

1 def render(request, *args, **kwargs): 2 """ 3 Returns a HttpResponse whose content is filled with the result of calling||返回的HttpResponse的内容充满了调用的结果 4 django.template.loader.render_to_string() with the passed arguments. 5 Uses a RequestCon

django源码分析---- Model类型&Field类型

djiango在数据库这方式自己实现了orm(object relationship mapping 对象关系模型映射).这个主要是用到python 元类这一 项python中的高级技术来实现的. class ModelBase(type): def __new__(cls,name,bases,attrs): # ..... pass pass class Model(metaclass=ModelBase): pass # 在这之后所有的用户自定义模型都继承自Model类 class Per

Django源码分析——URLS(还没弄明白)

1 def url(regex, view, kwargs=None, name=None, prefix=''): 2 if isinstance(view, (list,tuple)): 3 # For include(...) processing. 4 urlconf_module, app_name, namespace = view 5 return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name,