PageRenderTime 38ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

Plain Text | 587 lines | 380 code | 207 blank | 0 comment | 0 complexity | 9b9d168490653e4a1dc7e185754468d0 MD5 | raw file
Possible License(s): BSD-3-Clause
  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:
  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
  37. (or ``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 :setting:`CACHE_MIDDLEWARE_SECONDS`
  46. setting is 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``.
  52. Existing 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
  55. request phase because it pulls the list of headers to take into account
  56. from the global path registry and uses those to build a cache key to
  57. 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
  64. without building the response object itself. The headers are named in
  65. the ``Vary`` header of the response, but we want to prevent response
  66. generation.
  67. The list of headers to use for cache key generation is stored in the same
  68. cache as the pages themselves. If the cache ages some data out of the
  69. cache, this just means that we have to build the response once to get at
  70. the Vary header and so at the list of headers to use for the cache key.
  71. SortedDict
  72. ==========
  73. .. module:: django.utils.datastructures
  74. :synopsis: A dictionary that keeps its keys in the order in which they're inserted.
  75. .. class:: SortedDict
  76. The :class:`django.utils.datastructures.SortedDict` class is a dictionary
  77. that keeps its keys in the order in which they're inserted.
  78. ``SortedDict`` adds two additional methods to the standard Python ``dict``
  79. class:
  80. .. method:: insert(index, key, value)
  81. Inserts the key, value pair before the item with the given index.
  82. .. method:: value_for_index(index)
  83. Returns the value of the item at the given zero-based index.
  84. Creating a new SortedDict
  85. -------------------------
  86. Creating a new ``SortedDict`` must be done in a way where ordering is
  87. guaranteed. For example::
  88. SortedDict({'b': 1, 'a': 2, 'c': 3})
  89. will not work. Passing in a basic Python ``dict`` could produce unreliable
  90. results. Instead do::
  91. SortedDict([('b', 1), ('a', 2), ('c', 3)])
  92. ``django.utils.encoding``
  93. =========================
  94. .. module:: django.utils.encoding
  95. :synopsis: A series of helper classes and function to manage character encoding.
  96. .. class:: StrAndUnicode
  97. A class whose ``__str__`` returns its ``__unicode__`` as a UTF-8
  98. bytestring. Useful as a mix-in.
  99. .. function:: smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  100. Returns a ``unicode`` object representing ``s``. Treats bytestrings using
  101. the 'encoding' codec.
  102. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  103. objects.
  104. .. function:: is_protected_type(obj)
  105. Determine if the object instance is of a protected type.
  106. Objects of protected types are preserved as-is when passed to
  107. ``force_unicode(strings_only=True)``.
  108. .. function:: force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  109. Similar to ``smart_unicode``, except that lazy instances are resolved to
  110. strings, rather than kept as lazy objects.
  111. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  112. objects.
  113. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
  114. Returns a bytestring version of ``s``, encoded as specified in
  115. ``encoding``.
  116. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  117. objects.
  118. .. function:: iri_to_uri(iri)
  119. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  120. portion that is suitable for inclusion in a URL.
  121. This is the algorithm from section 3.1 of `RFC 3987`_. However, since we
  122. are assuming input is either UTF-8 or unicode already, we can simplify
  123. things a little from the full method.
  124. .. _RFC 3987:
  125. Returns an ASCII string containing the encoded result.
  126. ``django.utils.feedgenerator``
  127. ==============================
  128. .. module:: django.utils.feedgenerator
  129. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  130. Sample usage::
  131. >>> from django.utils import feedgenerator
  132. >>> feed = feedgenerator.Rss201rev2Feed(
  133. ... title=u"Poynter E-Media Tidbits",
  134. ... link=u"",
  135. ... description=u"A group Weblog by the sharpest minds in online media/journalism/publishing.",
  136. ... language=u"en",
  137. ... )
  138. >>> feed.add_item(
  139. ... title="Hello",
  140. ... link=u"",
  141. ... description="Testing."
  142. ... )
  143. >>> fp = open('test.rss', 'w')
  144. >>> feed.write(fp, 'utf-8')
  145. >>> fp.close()
  146. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  147. which is currently ``Rss201rev2Feed``
  148. For definitions of the different versions of RSS, see:
  150. .. function:: get_tag_uri(url, date)
  151. Creates a TagURI.
  152. See
  153. SyndicationFeed
  154. ---------------
  155. .. class:: SyndicationFeed
  156. Base class for all syndication feeds. Subclasses should provide write().
  157. .. method:: __init__(title, link, description, [language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs])
  158. Initialize the feed with the given dictionary of metadata, which applies
  159. to the entire feed.
  160. Any extra keyword arguments you pass to ``__init__`` will be stored in
  161. ``self.feed``.
  162. All parameters should be Unicode objects, except ``categories``, which
  163. should be a sequence of Unicode objects.
  164. .. 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])
  165. Adds an item to the feed. All args are expected to be Python ``unicode``
  166. objects except ``pubdate``, which is a ``datetime.datetime`` object, and
  167. ``enclosure``, which is an instance of the ``Enclosure`` class.
  168. .. method:: num_items()
  169. .. method:: root_attributes()
  170. Return extra attributes to place on the root (i.e. feed/channel)
  171. element. Called from ``write()``.
  172. .. method:: add_root_elements(handler)
  173. Add elements in the root (i.e. feed/channel) element.
  174. Called from ``write()``.
  175. .. method:: item_attributes(item)
  176. Return extra attributes to place on each item (i.e. item/entry)
  177. element.
  178. .. method:: add_item_elements(handler, item)
  179. Add elements on each item (i.e. item/entry) element.
  180. .. method:: write(outfile, encoding)
  181. Outputs the feed in the given encoding to ``outfile``, which is a
  182. file-like object. Subclasses should override this.
  183. .. method:: writeString(encoding)
  184. Returns the feed in the given encoding as a string.
  185. .. method:: latest_post_date()
  186. Returns the latest item's ``pubdate``. If none of them have a
  187. ``pubdate``, this returns the current date/time.
  188. Enclosure
  189. ---------
  190. .. class:: Enclosure
  191. Represents an RSS enclosure
  192. RssFeed
  193. -------
  194. .. class:: RssFeed(SyndicationFeed)
  195. Rss201rev2Feed
  196. --------------
  197. .. class:: Rss201rev2Feed(RssFeed)
  198. Spec:
  199. RssUserland091Feed
  200. ------------------
  201. .. class:: RssUserland091Feed(RssFeed)
  202. Spec:
  203. Atom1Feed
  204. ---------
  205. .. class:: Atom1Feed(SyndicationFeed)
  206. Spec:
  207. ``django.utils.functional``
  208. ===========================
  209. .. module:: django.utils.functional
  210. :synopsis: Functional programming tools.
  211. .. function:: allow_lazy(func, *resultclasses)
  212. Django offers many utility functions (particularly in ``django.utils``) that
  213. take a string as their first argument and do something to that string. These
  214. functions are used by template filters as well as directly in other code.
  215. If you write your own similar functions and deal with translations, you'll
  216. face the problem of what to do when the first argument is a lazy translation
  217. object. You don't want to convert it to a string immediately, because you might
  218. be using this function outside of a view (and hence the current thread's locale
  219. setting will not be correct).
  220. For cases like this, use the ``django.utils.functional.allow_lazy()``
  221. decorator. It modifies the function so that *if* it's called with a lazy
  222. translation as the first argument, the function evaluation is delayed until it
  223. needs to be converted to a string.
  224. For example::
  225. from django.utils.functional import allow_lazy
  226. def fancy_utility_function(s, ...):
  227. # Do some conversion on string 's'
  228. ...
  229. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  230. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  231. a number of extra arguments (``*args``) specifying the type(s) that the
  232. original function can return. Usually, it's enough to include ``unicode`` here
  233. and ensure that your function returns only Unicode strings.
  234. Using this decorator means you can write your function and assume that the
  235. input is a proper string, then add support for lazy translation objects at the
  236. end.
  237. ``django.utils.http``
  238. =====================
  239. .. module:: django.utils.http
  240. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  241. .. function:: urlquote(url, safe='/')
  242. A version of Python's ``urllib.quote()`` function that can operate on
  243. unicode strings. The url is first UTF-8 encoded before quoting. The
  244. returned string can safely be used as part of an argument to a subsequent
  245. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  246. execution.
  247. .. function:: urlquote_plus(url, safe='')
  248. A version of Python's urllib.quote_plus() function that can operate on
  249. unicode strings. The url is first UTF-8 encoded before quoting. The
  250. returned string can safely be used as part of an argument to a subsequent
  251. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  252. execution.
  253. .. function:: urlencode(query, doseq=0)
  254. A version of Python's urllib.urlencode() function that can operate on
  255. unicode strings. The parameters are first case to UTF-8 encoded strings
  256. and then encoded as per normal.
  257. .. function:: cookie_date(epoch_seconds=None)
  258. Formats the time to ensure compatibility with Netscape's cookie standard.
  259. Accepts a floating point number expressed in seconds since the epoch in
  260. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  261. defaults to the current time.
  262. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  263. .. function:: http_date(epoch_seconds=None)
  264. Formats the time to match the RFC 1123 date format as specified by HTTP
  265. `RFC 2616`_ section 3.3.1.
  266. .. _RFC 2616:
  267. Accepts a floating point number expressed in seconds since the epoch in
  268. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  269. defaults to the current time.
  270. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  271. .. function:: base36_to_int(s)
  272. Converts a base 36 string to an integer.
  273. .. function:: int_to_base36(i)
  274. Converts an integer to a base 36 string.
  275. ``django.utils.safestring``
  276. ===========================
  277. .. module:: django.utils.safestring
  278. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  279. Functions and classes for working with "safe strings": strings that can be
  280. displayed safely without further escaping in HTML. Marking something as a "safe
  281. string" means that the producer of the string has already turned characters
  282. that should not be interpreted by the HTML engine (e.g. '<') into the
  283. appropriate entities.
  284. .. class:: SafeString
  285. A string subclass that has been specifically marked as "safe" (requires no
  286. further escaping) for HTML output purposes.
  287. .. class:: SafeUnicode
  288. A unicode subclass that has been specifically marked as "safe" for HTML
  289. output purposes.
  290. .. function:: mark_safe(s)
  291. Explicitly mark a string as safe for (HTML) output purposes. The returned
  292. object can be used everywhere a string or unicode object is appropriate.
  293. Can be called multiple times on a single string.
  294. .. function:: mark_for_escaping(s)
  295. Explicitly mark a string as requiring HTML escaping upon output. Has no
  296. effect on ``SafeData`` subclasses.
  297. Can be called multiple times on a single string (the resulting escaping is
  298. only applied once).
  299. ``django.utils.translation``
  300. ============================
  301. .. module:: django.utils.translation
  302. :synopsis: Internationalization support.
  303. For a complete discussion on the usage of the following see the
  304. :doc:`Internationalization documentation </topics/i18n/internationalization>`.
  305. .. function:: gettext(message)
  306. Translates ``message`` and returns it in a UTF-8 bytestring
  307. .. function:: ugettext(message)
  308. Translates ``message`` and returns it in a unicode string
  309. .. function:: pgettext(context, message)
  310. Translates ``message`` given the ``context`` and returns
  311. it in a unicode string.
  312. For more information, see :ref:`contextual-markers`.
  313. .. function:: gettext_lazy(message)
  314. .. function:: ugettext_lazy(message)
  315. .. function:: pgettext_lazy(context, message)
  316. Same as the non-lazy versions above, but using lazy execution.
  317. See :ref:`lazy translations documentation <lazy-translations>`.
  318. .. function:: gettext_noop(message)
  319. .. function:: ugettext_noop(message)
  320. Marks strings for translation but doesn't translate them now. This can be
  321. used to store strings in global variables that should stay in the base
  322. language (because they might be used externally) and will be translated
  323. later.
  324. .. function:: ngettext(singular, plural, number)
  325. Translates ``singular`` and ``plural`` and returns the appropriate string
  326. based on ``number`` in a UTF-8 bytestring.
  327. .. function:: ungettext(singular, plural, number)
  328. Translates ``singular`` and ``plural`` and returns the appropriate string
  329. based on ``number`` in a unicode string.
  330. .. function:: npgettext(context, singular, plural, number)
  331. Translates ``singular`` and ``plural`` and returns the appropriate string
  332. based on ``number`` and the ``context`` in a unicode string.
  333. .. function:: ngettext_lazy(singular, plural, number)
  334. .. function:: ungettext_lazy(singular, plural, number)
  335. .. function:: npgettext_lazy(singular, plural, number)
  336. Same as the non-lazy versions above, but using lazy execution.
  337. See :ref:`lazy translations documentation <lazy-translations>`.
  338. .. function:: string_concat(*strings)
  339. Lazy variant of string concatenation, needed for translations that are
  340. constructed from multiple parts.
  341. .. function:: activate(language)
  342. Fetches the translation object for a given tuple of application name and
  343. language and installs it as the current translation object for the current
  344. thread.
  345. .. function:: deactivate()
  346. De-installs the currently active translation object so that further _ calls
  347. will resolve against the default translation object, again.
  348. .. function:: deactivate_all()
  349. Makes the active translation object a NullTranslations() instance. This is
  350. useful when we want delayed translations to appear as the original string
  351. for some reason.
  352. .. function:: get_language()
  353. Returns the currently selected language code.
  354. .. function:: get_language_bidi()
  355. Returns selected language's BiDi layout:
  356. * ``False`` = left-to-right layout
  357. * ``True`` = right-to-left layout
  358. .. function:: get_date_formats()
  359. Checks whether translation files provide a translation for some technical
  360. message ID to store date and time formats. If it doesn't contain one, the
  361. formats provided in the settings will be used.
  362. .. function:: get_language_from_request(request)
  363. Analyzes the request to find what language the user wants the system to show.
  364. Only languages listed in settings.LANGUAGES are taken into account. If the user
  365. requests a sublanguage where we have a main language, we send out the main
  366. language.
  367. .. function:: to_locale(language)
  368. Turns a language name (en-us) into a locale name (en_US).
  369. .. function:: templatize(src)
  370. Turns a Django template into something that is understood by xgettext. It does
  371. so by translating the Django translation tags into standard gettext function
  372. invocations.
  373. ``django.utils.tzinfo``
  374. =======================
  375. .. module:: django.utils.tzinfo
  376. :synopsis: Implementation of ``tzinfo`` classes for use with ``datetime.datetime``.
  377. .. class:: FixedOffset
  378. Fixed offset in minutes east from UTC.
  379. .. class:: LocalTimezone
  380. Proxy timezone information from time module.