utils.txt 16 KB

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