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

HttpResponse objects


In contrast to HttpRequest objects, which are created automatically by Django, HttpResponse objects are your responsibility. Each view you write is responsible for instantiating, populating and returning an HttpResponse.

The HttpResponse class lives in the django.http module.

Usage

Passing strings

Typical usage is to pass the contents of the page, as a string, to the HttpResponse constructor:

>>> from django.http import HttpResponse 
>>> response = HttpResponse("Here's the text of the Web page.") 
>>> response = HttpResponse("Text only, please.",
   content_type="text/plain")

But if you want to add content incrementally, you can use response as a file-like object:

>>> response = HttpResponse() 
>>> response.write("<p>Here's the text of the Web page.</p>") 
>>> response.write("<p>Here's another paragraph.</p>")

Passing iterators

Finally, you can pass HttpResponse an iterator rather than strings. HttpResponse will consume the iterator immediately, store its content as a string, and discard it.

If you need the response to be streamed from the iterator to the client, you must use the StreamingHttpResponse class instead.

Setting header fields

To set or remove a header field in your response, treat it like a dictionary:

>>> response = HttpResponse() 
>>> response['Age'] = 120 
>>> del response['Age']

Note that unlike a dictionary, del doesn't raise KeyError if the header field doesn't exist.

For setting the Cache-Control and Vary header fields, it is recommended to use the patch_cache_control() and patch_vary_headers() methods from django.utils.cache, since these fields can have multiple, comma-separated values. The patch methods ensure that other values, for example, added by a middleware, are not removed.

HTTP header fields cannot contain newlines. An attempt to set a header field containing a newline character (CR or LF) will raise BadHeaderError.

Telling the browser to treat the response as a file attachment

To tell the browser to treat the response as a file attachment, use the content_type argument and set the Content-Disposition header. For example, this is how you might return a Microsoft Excel spreadsheet:

>>> response = HttpResponse
  (my_data, content_type='application/vnd.ms-excel') 
>>> response['Content-Disposition'] = 'attachment; filename="foo.xls"'

There's nothing Django-specific about the Content-Disposition header, but it's easy to forget the syntax, so we've included it here.

Attributes

HttpResponse.content

A bytestring representing the content, encoded from a Unicode object if necessary.

HttpResponse.charset

A string denoting the charset in which the response will be encoded. If not given at HttpResponse instantiation time, it will be extracted from content_type and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.

HttpResponse.status_code

The HTTP status code for the response.

HttpResponse.reason_phrase

The HTTP reason phrase for the response.

HttpResponse.streaming

This is always False.

This attribute exists so middleware can treat streaming responses differently from regular responses.

HttpResponse.closed

True if the response has been closed.

Methods

HttpResponse.__init__()

HttpResponse.__init__(content='', 
  content_type=None, status=200, reason=None, charset=None) 

Instantiates an HttpResponse object with the given page content and content type. content should be an iterator or a string. If it's an iterator, it should return strings, and those strings will be joined together to form the content of the response. If it is not an iterator or a string, it will be converted to a string when accessed. Has four parameters:

  • content_type is the MIME type optionally completed by a character set encoding and is used to fill the HTTP Content-Type header. If not specified, it is formed by the DEFAULT_CONTENT_TYPE and DEFAULT_CHARSET settings, by default: text/html; charset=utf-8.
  • status is the HTTP status code for the response.
  • reason is the HTTP response phrase. If not provided, a default phrase will be used.
  • charset is the charset in which the response will be encoded. If not given it will be extracted from content_type, and if that is unsuccessful, the DEFAULT_CHARSET setting will be used.

HttpResponse.__setitem__(header, value)

Sets the given header name to the given value. Both header and value should be strings.

HttpResponse.__delitem__(header)

Deletes the header with the given name. Fails silently if the header doesn't exist. Case-insensitive.

HttpResponse.__getitem__(header)

Returns the value for the given header name. Case-insensitive.

HttpResponse.has_header(header)

Returns True or False based on a case-insensitive check for a header with the given name.

HttpResponse.setdefault(header, value)

Sets a header unless it has already been set.

HttpResponse.set_cookie()

HttpResponse.set_cookie(key, value='', 
  max_age=None, expires=None, path='/', 
  domain=None, secure=None, httponly=False) 

Sets a cookie. The parameters are the same as in the Morsel cookie object in the Python standard library.

  • max_age should be a number of seconds, or None (default) if the cookie should last only as long as the client's browser session. If expires is not specified, it will be calculated.
  • expires should either be a string in the format "Wdy, DD-Mon-YY HH:MM:SS GMT" or a datetime.datetime object in UTC. If expires is a datetime object, the max_age will be calculated.
  • Use domain if you want to set a cross-domain cookie. For example, domain=".lawrence.com" will set a cookie that is readable by the domains www.lawrence.com, blogs.lawrence.com and calendars.lawrence.com. Otherwise, a cookie will only be readable by the domain that set it.
  • Use httponly=True if you want to prevent client-side JavaScript from having access to the cookie.

HTTPOnly is a flag included in a Set-Cookie HTTP response header. It is not part of the RFC 2109 standard for cookies, and it isn't honored consistently by all browsers. However, when it is honored, it can be a useful way to mitigate the risk of client side script accessing the protected cookie data.

HttpResponse.set_signed_cookie()

Like set_cookie(), but cryptographic signing the cookie before setting it. Use in conjunction with HttpRequest.get_signed_cookie(). You can use the optional salt argument for added key strength, but you will need to remember to pass it to the corresponding HttpRequest.get_signed_cookie() call.

HttpResponse.delete_cookie()

Deletes the cookie with the given key. Fails silently if the key doesn't exist.

Due to the way cookies work, path and domain should be the same values you used in set_cookie()-otherwise the cookie may not be deleted.

HttpResponse.write(content)

HttpResponse.flush()

HttpResponse.tell()

These methods implement a file-like interface with an HttpResponse. They work the same way as the corresponding Python file method.

HttpResponse.getvalue()

Returns the value of HttpResponse.content. This method makes an HttpResponse instance a stream-like object.

HttpResponse.writable()

Always True. This method makes an HttpResponse instance a stream-like object.

HttpResponse.writelines(lines)

Writes a list of lines to the response. Line separators are not added. This method makes an HttpResponse instance a stream-like object.

HttpResponse subclasses

Django includes a number of HttpResponse subclasses that handle different types of HTTP responses. Like HttpResponse, these subclasses live in django.http.

HttpResponseRedirect

The first argument to the constructor is required-the path to redirect to. This can be a fully qualified URL (for example, http://www.yahoo.com/search/) or an absolute path with no domain (for example, /search/). See HttpResponse for other optional constructor arguments. Note that this returns an HTTP status code 302.

HttpResponsePermanentRedirect

Like HttpResponseRedirect, but it returns a permanent redirect (HTTP status code 301) instead of a found redirect (status code 302).

HttpResponseNotModified

The constructor doesn't take any arguments and no content should be added to this response. Use this to designate that a page hasn't been modified since the user's last request (status code 304).

HttpResponseBadRequest

Acts just like HttpResponse but uses a 400 status code.

HttpResponseNotFound

Acts just like HttpResponse but uses a 404 status code.

HttpResponseForbidden

Acts just like HttpResponse but uses a 403 status code.

HttpResponseNotAllowed

Like HttpResponse, but uses a 405 status code. The first argument to the constructor is required: a list of permitted methods (for example, ['GET', 'POST']).

HttpResponseGone

Acts just like HttpResponse but uses a 410 status code.

HttpResponseServerError

Acts just like HttpResponse but uses a 500 status code.

If a custom subclass of HttpResponse implements a render method, Django will treat it as emulating a SimpleTemplateResponse, and the render method must itself return a valid response object.