utils.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. ============
  2. Django Utils
  3. ============
  4. .. module:: django.utils
  5. :synopsis: Django's built-in utilities.
  6. This document covers all stable modules in ``django.utils``. Most of the
  7. modules in ``django.utils`` are designed for internal use and only the
  8. following parts can be considered stable and thus backwards compatible as per
  9. the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`.
  10. ``django.utils.cache``
  11. ======================
  12. .. module:: django.utils.cache
  13. :synopsis: Helper functions for controlling caching.
  14. This module contains helper functions for controlling caching. It does so by
  15. managing the ``Vary`` header of responses. It includes functions to patch the
  16. header of response objects directly and decorators that change functions to do
  17. that header-patching themselves.
  18. For information on the ``Vary`` header, see `RFC 2616 section 14.44`_.
  19. .. _RFC 2616 section 14.44: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.44
  20. Essentially, the ``Vary`` HTTP header defines which headers a cache should take
  21. into account when building its cache key. Requests with the same path but
  22. different header content for headers named in ``Vary`` need to get different
  23. cache keys to prevent delivery of wrong content.
  24. For example, :doc:`internationalization </topics/i18n/index>` middleware would need
  25. to distinguish caches by the ``Accept-language`` header.
  26. .. function:: patch_cache_control(response, **kwargs)
  27. This function patches the ``Cache-Control`` header by adding all keyword
  28. arguments to it. The transformation is as follows:
  29. * All keyword parameter names are turned to lowercase, and underscores
  30. are converted to hyphens.
  31. * If the value of a parameter is ``True`` (exactly ``True``, not just a
  32. true value), only the parameter name is added to the header.
  33. * All other parameters are added with their value, after applying
  34. ``str()`` to it.
  35. .. function:: get_max_age(response)
  36. Returns the max-age from the response Cache-Control header as an integer (or
  37. ``None`` if it wasn't found or wasn't an integer).
  38. .. function:: patch_response_headers(response, cache_timeout=None)
  39. Adds some useful headers to the given ``HttpResponse`` object:
  40. * ``ETag``
  41. * ``Last-Modified``
  42. * ``Expires``
  43. * ``Cache-Control``
  44. Each header is only added if it isn't already set.
  45. ``cache_timeout`` is in seconds. The ``CACHE_MIDDLEWARE_SECONDS`` setting is
  46. used by default.
  47. .. function:: add_never_cache_headers(response)
  48. Adds headers to a response to indicate that a page should never be cached.
  49. .. function:: patch_vary_headers(response, newheaders)
  50. Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
  51. ``newheaders`` is a list of header names that should be in ``Vary``. Existing
  52. headers in ``Vary`` aren't removed.
  53. .. function:: get_cache_key(request, key_prefix=None)
  54. Returns a cache key based on the request path. It can be used in the request
  55. phase because it pulls the list of headers to take into account from the
  56. global path registry and uses those to build a cache key to check against.
  57. If there is no headerlist stored, the page needs to be rebuilt, so this
  58. function returns ``None``.
  59. .. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None)
  60. Learns what headers to take into account for some request path from the
  61. response object. It stores those headers in a global path registry so that
  62. later access to that path will know what headers to take into account without
  63. building the response object itself. The headers are named in the ``Vary``
  64. header of the response, but we want to prevent response generation.
  65. The list of headers to use for cache key generation is stored in the same cache
  66. as the pages themselves. If the cache ages some data out of the cache, this
  67. just means that we have to build the response once to get at the Vary header
  68. and so at the list of headers to use for the cache key.
  69. SortedDict
  70. ==========
  71. .. module:: django.utils.datastructures
  72. :synopsis: A dictionary that keeps its keys in the order in which they're inserted.
  73. .. class:: django.utils.datastructures.SortedDict
  74. Methods
  75. -------
  76. Extra methods that ``SortedDict`` adds to the standard Python ``dict`` class.
  77. .. method:: insert(index, key, value)
  78. Inserts the key, value pair before the item with the given index.
  79. .. method:: value_for_index(index)
  80. Returns the value of the item at the given zero-based index.
  81. Creating new SortedDict
  82. -----------------------
  83. Creating a new ``SortedDict`` must be done in a way where ordering is
  84. guaranteed. For example::
  85. SortedDict({'b': 1, 'a': 2, 'c': 3})
  86. will not work. Passing in a basic Python ``dict`` could produce unreliable
  87. results. Instead do::
  88. SortedDict([('b', 1), ('a', 2), ('c', 3)])
  89. ``django.utils.encoding``
  90. =========================
  91. .. module:: django.utils.encoding
  92. :synopsis: A series of helper classes and function to manage character encoding.
  93. .. class:: StrAndUnicode
  94. A class whose ``__str__`` returns its ``__unicode__`` as a UTF-8 bytestring.
  95. Useful as a mix-in.
  96. .. function:: smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  97. Returns a ``unicode`` object representing ``s``. Treats bytestrings using the
  98. 'encoding' codec.
  99. If ``strings_only`` is ``True``, don't convert (some) non-string-like objects.
  100. .. function:: is_protected_type(obj)
  101. Determine if the object instance is of a protected type.
  102. Objects of protected types are preserved as-is when passed to
  103. ``force_unicode(strings_only=True)``.
  104. .. function:: force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  105. Similar to ``smart_unicode``, except that lazy instances are resolved to strings,
  106. rather than kept as lazy objects.
  107. If ``strings_only`` is ``True``, don't convert (some) non-string-like objects.
  108. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
  109. Returns a bytestring version of ``s``, encoded as specified in ``encoding``.
  110. If ``strings_only`` is ``True``, don't convert (some) non-string-like objects.
  111. .. function:: iri_to_uri(iri)
  112. Convert an Internationalized Resource Identifier (IRI) portion to a URI portion
  113. that is suitable for inclusion in a URL.
  114. This is the algorithm from section 3.1 of `RFC 3987`_. However, since we are
  115. assuming input is either UTF-8 or unicode already, we can simplify things a
  116. little from the full method.
  117. .. _RFC 3987: http://www.ietf.org/rfc/rfc3987.txt
  118. Returns an ASCII string containing the encoded result.
  119. ``django.utils.feedgenerator``
  120. ==============================
  121. .. module:: django.utils.feedgenerator
  122. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  123. Sample usage::
  124. >>> from django.utils import feedgenerator
  125. >>> feed = feedgenerator.Rss201rev2Feed(
  126. ... title=u"Poynter E-Media Tidbits",
  127. ... link=u"http://www.poynter.org/column.asp?id=31",
  128. ... description=u"A group Weblog by the sharpest minds in online media/journalism/publishing.",
  129. ... language=u"en",
  130. ... )
  131. >>> feed.add_item(
  132. ... title="Hello",
  133. ... link=u"http://www.holovaty.com/test/",
  134. ... description="Testing."
  135. ... )
  136. >>> fp = open('test.rss', 'w')
  137. >>> feed.write(fp, 'utf-8')
  138. >>> fp.close()
  139. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  140. which is currently ``Rss201rev2Feed``
  141. For definitions of the different versions of RSS, see:
  142. http://diveintomark.org/archives/2004/02/04/incompatible-rss
  143. .. function:: get_tag_uri(url, date)
  144. Creates a TagURI.
  145. See http://diveintomark.org/archives/2004/05/28/howto-atom-id
  146. SyndicationFeed
  147. ---------------
  148. .. class:: SyndicationFeed
  149. Base class for all syndication feeds. Subclasses should provide write().
  150. Methods
  151. ~~~~~~~
  152. .. method:: add_item(title, link, description, [author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None, **kwargs])
  153. Adds an item to the feed. All args are expected to be Python ``unicode``
  154. objects except ``pubdate``, which is a ``datetime.datetime`` object, and
  155. ``enclosure``, which is an instance of the ``Enclosure`` class.
  156. .. method:: num_items()
  157. .. method:: root_attributes()
  158. Return extra attributes to place on the root (i.e. feed/channel) element.
  159. Called from write().
  160. .. method:: add_root_elements(handler)
  161. Add elements in the root (i.e. feed/channel) element. Called from write().
  162. .. method:: item_attributes(item)
  163. Return extra attributes to place on each item (i.e. item/entry) element.
  164. .. method:: add_item_elements(handler, item)
  165. Add elements on each item (i.e. item/entry) element.
  166. .. method:: write(outfile, encoding)
  167. Outputs the feed in the given encoding to ``outfile``, which is a file-like
  168. object. Subclasses should override this.
  169. .. method:: writeString(encoding)
  170. Returns the feed in the given encoding as a string.
  171. .. method:: latest_post_date()
  172. Returns the latest item's ``pubdate``. If none of them have a ``pubdate``,
  173. this returns the current date/time.
  174. Enclosure
  175. ---------
  176. .. class:: Enclosure
  177. Represents an RSS enclosure
  178. RssFeed
  179. -------
  180. .. class:: RssFeed(SyndicationFeed)
  181. Rss201rev2Feed
  182. --------------
  183. .. class:: Rss201rev2Feed(RssFeed)
  184. Spec: http://blogs.law.harvard.edu/tech/rss
  185. Atom1Feed
  186. ---------
  187. .. class:: Atom1Feed(SyndicationFeed)
  188. Spec: http://atompub.org/2005/07/11/draft-ietf-atompub-format-10.html
  189. ``django.utils.http``
  190. =====================
  191. .. module:: django.utils.http
  192. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  193. .. function:: urlquote(url, safe='/')
  194. A version of Python's ``urllib.quote()`` function that can operate on unicode
  195. strings. The url is first UTF-8 encoded before quoting. The returned string
  196. can safely be used as part of an argument to a subsequent ``iri_to_uri()``
  197. call without double-quoting occurring. Employs lazy execution.
  198. .. function:: urlquote_plus(url, safe='')
  199. A version of Python's urllib.quote_plus() function that can operate on unicode
  200. strings. The url is first UTF-8 encoded before quoting. The returned string can
  201. safely be used as part of an argument to a subsequent iri_to_uri() call without
  202. double-quoting occurring. Employs lazy execution.
  203. .. function:: urlencode(query, doseq=0)
  204. A version of Python's urllib.urlencode() function that can operate on unicode
  205. strings. The parameters are first case to UTF-8 encoded strings and then
  206. encoded as per normal.
  207. .. function:: cookie_date(epoch_seconds=None)
  208. Formats the time to ensure compatibility with Netscape's cookie standard.
  209. Accepts a floating point number expressed in seconds since the epoch, in UTC -
  210. such as that outputted by ``time.time()``. If set to ``None``, defaults to the current
  211. time.
  212. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  213. .. function:: http_date(epoch_seconds=None)
  214. Formats the time to match the RFC 1123 date format as specified by HTTP
  215. `RFC 2616`_ section 3.3.1.
  216. .. _RFC 2616: http://www.w3.org/Protocols/rfc2616/rfc2616.txt
  217. Accepts a floating point number expressed in seconds since the epoch, in UTC -
  218. such as that outputted by ``time.time()``. If set to ``None``, defaults to the current
  219. time.
  220. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  221. .. function:: base36_to_int(s)
  222. Converted a base 36 string to an integer
  223. .. function:: int_to_base36(i)
  224. Converts an integer to a base36 string
  225. ``django.utils.safestring``
  226. ===========================
  227. .. module:: django.utils.safestring
  228. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  229. Functions and classes for working with "safe strings": strings that can be
  230. displayed safely without further escaping in HTML. Marking something as a "safe
  231. string" means that the producer of the string has already turned characters
  232. that should not be interpreted by the HTML engine (e.g. '<') into the
  233. appropriate entities.
  234. .. class:: SafeString
  235. A string subclass that has been specifically marked as "safe" (requires no
  236. further escaping) for HTML output purposes.
  237. .. class:: SafeUnicode
  238. A unicode subclass that has been specifically marked as "safe" for HTML output
  239. purposes.
  240. .. function:: mark_safe(s)
  241. Explicitly mark a string as safe for (HTML) output purposes. The returned
  242. object can be used everywhere a string or unicode object is appropriate.
  243. Can be called multiple times on a single string.
  244. .. function:: mark_for_escaping(s)
  245. Explicitly mark a string as requiring HTML escaping upon output. Has no effect
  246. on ``SafeData`` subclasses.
  247. Can be called multiple times on a single string (the resulting escaping is only
  248. applied once).
  249. ``django.utils.translation``
  250. ============================
  251. .. module:: django.utils.translation
  252. :synopsis: Internationalization support.
  253. For a complete discussion on the usage of the following see the
  254. :doc:`Internationalization documentation </topics/i18n/internationalization>`.
  255. .. function:: gettext(message)
  256. Translates ``message`` and returns it in a UTF-8 bytestring
  257. .. function:: ugettext(message)
  258. Translates ``message`` and returns it in a unicode string
  259. .. function:: gettext_lazy(message)
  260. .. function:: ugettext_lazy(message)
  261. Same as the non-lazy versions above, but using lazy execution.
  262. See :ref:`lazy translations documentation <lazy-translations>`.
  263. .. function:: gettext_noop(message)
  264. Marks strings for translation but doesn't translate them now. This can be used
  265. to store strings in global variables that should stay in the base language
  266. (because they might be used externally) and will be translated later.
  267. .. function:: ngettext(singular, plural, number)
  268. Translates ``singular`` and ``plural`` and returns the appropriate string
  269. based on ``number`` in a UTF-8 bytestring
  270. .. function:: ungettext(singular, plural, number)
  271. Translates ``singular`` and ``plural`` and returns the appropriate string based
  272. on ``number`` in a unicode string
  273. .. function:: ngettext_lazy(singular, plural, number)
  274. .. function:: ungettext_lazy(singular, plural, number)
  275. Same as the non-lazy versions above, but using lazy execution.
  276. See :ref:`lazy translations documentation <lazy-translations>`.
  277. .. function:: string_concat(*strings)
  278. Lazy variant of string concatenation, needed for translations that are
  279. constructed from multiple parts.
  280. .. function:: activate(language)
  281. Fetches the translation object for a given tuple of application name and
  282. language and installs it as the current translation object for the current
  283. thread.
  284. .. function:: deactivate()
  285. De-installs the currently active translation object so that further _ calls will
  286. resolve against the default translation object, again.
  287. .. function:: deactivate_all()
  288. Makes the active translation object a NullTranslations() instance. This is
  289. useful when we want delayed translations to appear as the original string for
  290. some reason.
  291. .. function:: get_language()
  292. Returns the currently selected language code.
  293. .. function:: get_language_bidi()
  294. Returns selected language's BiDi layout:
  295. * ``False`` = left-to-right layout
  296. * ``True`` = right-to-left layout
  297. .. function:: get_date_formats()
  298. Checks whether translation files provide a translation for some technical
  299. message ID to store date and time formats. If it doesn't contain one, the
  300. formats provided in the settings will be used.
  301. .. function:: get_language_from_request(request)
  302. Analyzes the request to find what language the user wants the system to show.
  303. Only languages listed in settings.LANGUAGES are taken into account. If the user
  304. requests a sublanguage where we have a main language, we send out the main
  305. language.
  306. .. function:: to_locale(language)
  307. Turns a language name (en-us) into a locale name (en_US).
  308. .. function:: templatize(src)
  309. Turns a Django template into something that is understood by xgettext. It does
  310. so by translating the Django translation tags into standard gettext function
  311. invocations.
  312. ``django.utils.tzinfo``
  313. =======================
  314. .. module:: django.utils.tzinfo
  315. :synopsis: Implementation of ``tzinfo`` classes for use with ``datetime.datetime``.
  316. .. class:: FixedOffset
  317. Fixed offset in minutes east from UTC.
  318. .. class:: LocalTimezone
  319. Proxy timezone information from time module.