Book Image

Mastering Django: Core

By : Nigel George
Book Image

Mastering Django: Core

By: Nigel George

Overview of this book

Mastering Django: Core is a completely revised and updated version of the original Django Book, written by Adrian Holovaty and Jacob Kaplan-Moss - the creators of Django. The main goal of this book is to make you a Django expert. By reading this book, you’ll learn the skills needed to develop powerful websites quickly, with code that is clean and easy to maintain. This book is also a programmer’s manual that provides complete coverage of the current Long Term Support (LTS) version of Django. For developers creating applications for commercial and business critical deployments, Mastering Django: Core provides a complete, up-to-date resource for Django 1.8LTS with a stable code-base, security fixes and support out to 2018.
Table of Contents (33 chapters)
Mastering Django: Core
Credits
About the Author
www.PacktPub.com
Preface
Free Chapter
1
Introduction to Django and Getting Started

StreamingHttpResponse objects


The StreamingHttpResponse class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory. For instance, it's useful for generating large CSV files.

Performance considerations

Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.

Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.

The StreamingHttpResponse is not a subclass of HttpResponse, because it features a slightly different API. However, it is almost identical, with the following notable differences:

  • It should be given an iterator that yields strings as content.
  • You cannot access its content, except by iterating the response object itself. This should only occur when the response is returned to the client.
  • It has no content attribute. Instead, it has a streaming_content attribute.
  • You cannot use the file-like object tell() or write() methods. Doing so will raise an exception.

StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn't iterated before transferring the data to the client. Because the content can't be accessed, many middlewares can't function normally. For example, the ETag and Content-Length headers can't be generated for streaming responses.

Attributes

StreamingHttpResponse has the following attributes:

  • * *.streaming_content. An iterator of strings representing the content.
  • * *.status_code. The HTTP status code for the response.
  • * *.reason_phrase. The HTTP reason phrase for the response.
  • * *.streaming. This is always True.