utils.txt 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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` section
  19. 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. ``django.utils.datastructures``
  72. ===============================
  73. .. module:: django.utils.datastructures
  74. :synopsis: Data structures that aren't in Python's standard library.
  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. .. deprecated:: 1.5
  82. Inserts the key, value pair before the item with the given index.
  83. .. method:: value_for_index(index)
  84. .. deprecated:: 1.5
  85. Returns the value of the item at the given zero-based index.
  86. Creating a new SortedDict
  87. -------------------------
  88. Creating a new ``SortedDict`` must be done in a way where ordering is
  89. guaranteed. For example::
  90. SortedDict({'b': 1, 'a': 2, 'c': 3})
  91. will not work. Passing in a basic Python ``dict`` could produce unreliable
  92. results. Instead do::
  93. SortedDict([('b', 1), ('a', 2), ('c', 3)])
  94. ``django.utils.dateparse``
  95. ==========================
  96. .. module:: django.utils.dateparse
  97. :synopsis: Functions to parse datetime objects.
  98. The functions defined in this module share the following properties:
  99. - They raise :exc:`~exceptions.ValueError` if their input is well formatted but
  100. isn't a valid date or time.
  101. - They return ``None`` if it isn't well formatted at all.
  102. - They accept up to picosecond resolution in input, but they truncate it to
  103. microseconds, since that's what Python supports.
  104. .. function:: parse_date(value)
  105. Parses a string and returns a :class:`datetime.date`.
  106. .. function:: parse_time(value)
  107. Parses a string and returns a :class:`datetime.time`.
  108. UTC offsets aren't supported; if ``value`` describes one, the result is
  109. ``None``.
  110. .. function:: parse_datetime(value)
  111. Parses a string and returns a :class:`datetime.datetime`.
  112. UTC offsets are supported; if ``value`` describes one, the result's
  113. ``tzinfo`` attribute is a :class:`~django.utils.tzinfo.FixedOffset`
  114. instance.
  115. ``django.utils.decorators``
  116. ===========================
  117. .. module:: django.utils.decorators
  118. :synopsis: Functions that help with creating decorators for views.
  119. .. function:: method_decorator(decorator)
  120. Converts a function decorator into a method decorator. See :ref:`decorating
  121. class based views<decorating-class-based-views>` for example usage.
  122. .. function:: decorator_from_middleware(middleware_class)
  123. Given a middleware class, returns a view decorator. This lets you use
  124. middleware functionality on a per-view basis. The middleware is created
  125. with no params passed.
  126. .. function:: decorator_from_middleware_with_args(middleware_class)
  127. Like ``decorator_from_middleware``, but returns a function
  128. that accepts the arguments to be passed to the middleware_class.
  129. For example, the :func:`~django.views.decorators.cache.cache_page`
  130. decorator is created from the ``CacheMiddleware`` like this::
  131. cache_page = decorator_from_middleware_with_args(CacheMiddleware)
  132. @cache_page(3600)
  133. def my_view(request):
  134. pass
  135. ``django.utils.encoding``
  136. =========================
  137. .. module:: django.utils.encoding
  138. :synopsis: A series of helper classes and function to manage character encoding.
  139. .. class:: StrAndUnicode
  140. A class that derives ``__str__`` from ``__unicode__``.
  141. On Python 2, ``__str__`` returns the output of ``__unicode__`` encoded as
  142. a UTF-8 bytestring. On Python 3, ``__str__`` returns the output of
  143. ``__unicode__``.
  144. Useful as a mix-in. If you support Python 2 and 3 with a single code base,
  145. you can inherit this mix-in and just define ``__unicode__``.
  146. .. function:: python_2_unicode_compatible
  147. A decorator that defines ``__unicode__`` and ``__str__`` methods under
  148. Python 2. Under Python 3 it does nothing.
  149. To support Python 2 and 3 with a single code base, define a ``__str__``
  150. method returning text and apply this decorator to the class.
  151. .. function:: smart_text(s, encoding='utf-8', strings_only=False, errors='strict')
  152. .. versionadded:: 1.5
  153. Returns a text object representing ``s`` -- ``unicode`` on Python 2 and
  154. ``str`` on Python 3. Treats bytestrings using the ``encoding`` codec.
  155. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  156. objects.
  157. .. function:: smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  158. Historical name of :func:`smart_text`. Only available under Python 2.
  159. .. function:: is_protected_type(obj)
  160. Determine if the object instance is of a protected type.
  161. Objects of protected types are preserved as-is when passed to
  162. ``force_text(strings_only=True)``.
  163. .. function:: force_text(s, encoding='utf-8', strings_only=False, errors='strict')
  164. .. versionadded:: 1.5
  165. Similar to ``smart_text``, except that lazy instances are resolved to
  166. strings, rather than kept as lazy objects.
  167. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  168. objects.
  169. .. function:: force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  170. Historical name of :func:`force_text`. Only available under Python 2.
  171. .. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  172. .. versionadded:: 1.5
  173. Returns a bytestring version of ``s``, encoded as specified in
  174. ``encoding``.
  175. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  176. objects.
  177. .. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  178. .. versionadded:: 1.5
  179. Similar to ``smart_bytes``, except that lazy instances are resolved to
  180. bytestrings, rather than kept as lazy objects.
  181. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  182. objects.
  183. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
  184. Alias of :func:`smart_bytes` on Python 2 and :func:`smart_text` on Python
  185. 3. This function returns a ``str`` or a lazy string.
  186. For instance, this is suitable for writing to :data:`sys.stdout` on
  187. Python 2 and 3.
  188. .. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
  189. Alias of :func:`force_bytes` on Python 2 and :func:`force_text` on Python
  190. 3. This function always returns a ``str``.
  191. .. function:: iri_to_uri(iri)
  192. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  193. portion that is suitable for inclusion in a URL.
  194. This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`. However,
  195. since we are assuming input is either UTF-8 or unicode already, we can
  196. simplify things a little from the full method.
  197. Returns an ASCII string containing the encoded result.
  198. .. function:: filepath_to_uri(path)
  199. Convert a file system path to a URI portion that is suitable for inclusion
  200. in a URL. The path is assumed to be either UTF-8 or unicode.
  201. This method will encode certain characters that would normally be
  202. recognized as special characters for URIs. Note that this method does not
  203. encode the ' character, as it is a valid character within URIs. See
  204. ``encodeURIComponent()`` JavaScript function for more details.
  205. Returns an ASCII string containing the encoded result.
  206. ``django.utils.feedgenerator``
  207. ==============================
  208. .. module:: django.utils.feedgenerator
  209. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  210. Sample usage::
  211. >>> from django.utils import feedgenerator
  212. >>> feed = feedgenerator.Rss201rev2Feed(
  213. ... title=u"Poynter E-Media Tidbits",
  214. ... link=u"http://www.poynter.org/column.asp?id=31",
  215. ... description=u"A group Weblog by the sharpest minds in online media/journalism/publishing.",
  216. ... language=u"en",
  217. ... )
  218. >>> feed.add_item(
  219. ... title="Hello",
  220. ... link=u"http://www.holovaty.com/test/",
  221. ... description="Testing."
  222. ... )
  223. >>> with open('test.rss', 'w') as fp:
  224. ... feed.write(fp, 'utf-8')
  225. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  226. which is currently ``Rss201rev2Feed``
  227. For definitions of the different versions of RSS, see:
  228. http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  229. .. function:: get_tag_uri(url, date)
  230. Creates a TagURI.
  231. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  232. SyndicationFeed
  233. ---------------
  234. .. class:: SyndicationFeed
  235. Base class for all syndication feeds. Subclasses should provide write().
  236. .. 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])
  237. Initialize the feed with the given dictionary of metadata, which applies
  238. to the entire feed.
  239. Any extra keyword arguments you pass to ``__init__`` will be stored in
  240. ``self.feed``.
  241. All parameters should be Unicode objects, except ``categories``, which
  242. should be a sequence of Unicode objects.
  243. .. 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])
  244. Adds an item to the feed. All args are expected to be Python ``unicode``
  245. objects except ``pubdate``, which is a ``datetime.datetime`` object, and
  246. ``enclosure``, which is an instance of the ``Enclosure`` class.
  247. .. method:: num_items()
  248. .. method:: root_attributes()
  249. Return extra attributes to place on the root (i.e. feed/channel)
  250. element. Called from ``write()``.
  251. .. method:: add_root_elements(handler)
  252. Add elements in the root (i.e. feed/channel) element.
  253. Called from ``write()``.
  254. .. method:: item_attributes(item)
  255. Return extra attributes to place on each item (i.e. item/entry)
  256. element.
  257. .. method:: add_item_elements(handler, item)
  258. Add elements on each item (i.e. item/entry) element.
  259. .. method:: write(outfile, encoding)
  260. Outputs the feed in the given encoding to ``outfile``, which is a
  261. file-like object. Subclasses should override this.
  262. .. method:: writeString(encoding)
  263. Returns the feed in the given encoding as a string.
  264. .. method:: latest_post_date()
  265. Returns the latest item's ``pubdate``. If none of them have a
  266. ``pubdate``, this returns the current date/time.
  267. Enclosure
  268. ---------
  269. .. class:: Enclosure
  270. Represents an RSS enclosure
  271. RssFeed
  272. -------
  273. .. class:: RssFeed(SyndicationFeed)
  274. Rss201rev2Feed
  275. --------------
  276. .. class:: Rss201rev2Feed(RssFeed)
  277. Spec: http://cyber.law.harvard.edu/rss/rss.html
  278. RssUserland091Feed
  279. ------------------
  280. .. class:: RssUserland091Feed(RssFeed)
  281. Spec: http://backend.userland.com/rss091
  282. Atom1Feed
  283. ---------
  284. .. class:: Atom1Feed(SyndicationFeed)
  285. Spec: http://www.atomenabled.org/developers/syndication/atom-format-spec.php
  286. ``django.utils.functional``
  287. ===========================
  288. .. module:: django.utils.functional
  289. :synopsis: Functional programming tools.
  290. .. function:: allow_lazy(func, *resultclasses)
  291. Django offers many utility functions (particularly in ``django.utils``) that
  292. take a string as their first argument and do something to that string. These
  293. functions are used by template filters as well as directly in other code.
  294. If you write your own similar functions and deal with translations, you'll
  295. face the problem of what to do when the first argument is a lazy translation
  296. object. You don't want to convert it to a string immediately, because you might
  297. be using this function outside of a view (and hence the current thread's locale
  298. setting will not be correct).
  299. For cases like this, use the ``django.utils.functional.allow_lazy()``
  300. decorator. It modifies the function so that *if* it's called with a lazy
  301. translation as the first argument, the function evaluation is delayed until it
  302. needs to be converted to a string.
  303. For example::
  304. from django.utils.functional import allow_lazy
  305. def fancy_utility_function(s, ...):
  306. # Do some conversion on string 's'
  307. ...
  308. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  309. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  310. a number of extra arguments (``*args``) specifying the type(s) that the
  311. original function can return. Usually, it's enough to include ``unicode`` here
  312. and ensure that your function returns only Unicode strings.
  313. Using this decorator means you can write your function and assume that the
  314. input is a proper string, then add support for lazy translation objects at the
  315. end.
  316. ``django.utils.html``
  317. =====================
  318. .. module:: django.utils.html
  319. :synopsis: HTML helper functions
  320. Usually you should build up HTML using Django's templates to make use of its
  321. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
  322. where appropriate. This module provides some additional low level utilitiesfor
  323. escaping HTML.
  324. .. function:: escape(text)
  325. Returns the given text with ampersands, quotes and angle brackets encoded
  326. for use in HTML. The input is first passed through
  327. :func:`~django.utils.encoding.force_text` and the output has
  328. :func:`~django.utils.safestring.mark_safe` applied.
  329. .. function:: conditional_escape(text)
  330. Similar to ``escape()``, except that it doesn't operate on pre-escaped strings,
  331. so it will not double escape.
  332. .. function:: format_html(format_string, *args, **kwargs)
  333. This is similar to `str.format`_, except that it is appropriate for
  334. building up HTML fragments. All args and kwargs are passed through
  335. :func:`conditional_escape` before being passed to ``str.format``.
  336. For the case of building up small HTML fragments, this function is to be
  337. preferred over string interpolation using ``%`` or ``str.format`` directly,
  338. because it applies escaping to all arguments - just like the Template system
  339. applies escaping by default.
  340. So, instead of writing:
  341. .. code-block:: python
  342. mark_safe(u"%s <b>%s</b> %s" % (some_html,
  343. escape(some_text),
  344. escape(some_other_text),
  345. ))
  346. you should instead use:
  347. .. code-block:: python
  348. format_html(u"{0} <b>{1}</b> {2}",
  349. mark_safe(some_html), some_text, some_other_text)
  350. This has the advantage that you don't need to apply :func:`escape` to each
  351. argument and risk a bug and an XSS vulnerability if you forget one.
  352. Note that although this function uses ``str.format`` to do the
  353. interpolation, some of the formatting options provided by `str.format`_
  354. (e.g. number formatting) will not work, since all arguments are passed
  355. through :func:`conditional_escape` which (ultimately) calls
  356. :func:`~django.utils.encoding.force_text` on the values.
  357. .. function:: format_html_join(sep, format_string, args_generator)
  358. A wrapper of :func:`format_html`, for the common case of a group of
  359. arguments that need to be formatted using the same format string, and then
  360. joined using ``sep``. ``sep`` is also passed through
  361. :func:`conditional_escape`.
  362. ``args_generator`` should be an iterator that returns the sequence of
  363. ``args`` that will be passed to :func:`format_html`. For example::
  364. format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
  365. for u in users))
  366. .. function:: strip_tags(value)
  367. Removes anything that looks like an html tag from the string, that is
  368. anything contained within ``<>``.
  369. For example::
  370. strip_tags(value)
  371. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  372. return value will be ``"Joel is a slug"``.
  373. .. function:: remove_tags(value, tags)
  374. Removes a list of [X]HTML tag names from the output.
  375. For example::
  376. remove_tags(value, ["b", "span"])
  377. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  378. return value will be ``"Joel <button>is</button> a slug"``.
  379. Note that this filter is case-sensitive.
  380. If ``value`` is ``"<B>Joel</B> <button>is</button> a <span>slug</span>"`` the
  381. return value will be ``"<B>Joel</B> <button>is</button> a slug"``.
  382. .. _str.format: http://docs.python.org/library/stdtypes.html#str.format
  383. ``django.utils.http``
  384. =====================
  385. .. module:: django.utils.http
  386. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  387. .. function:: urlquote(url, safe='/')
  388. A version of Python's ``urllib.quote()`` function that can operate on
  389. unicode strings. The url is first UTF-8 encoded before quoting. The
  390. returned string can safely be used as part of an argument to a subsequent
  391. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  392. execution.
  393. .. function:: urlquote_plus(url, safe='')
  394. A version of Python's urllib.quote_plus() function that can operate on
  395. unicode strings. The url is first UTF-8 encoded before quoting. The
  396. returned string can safely be used as part of an argument to a subsequent
  397. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  398. execution.
  399. .. function:: urlencode(query, doseq=0)
  400. A version of Python's urllib.urlencode() function that can operate on
  401. unicode strings. The parameters are first case to UTF-8 encoded strings
  402. and then encoded as per normal.
  403. .. function:: cookie_date(epoch_seconds=None)
  404. Formats the time to ensure compatibility with Netscape's cookie standard.
  405. Accepts a floating point number expressed in seconds since the epoch in
  406. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  407. defaults to the current time.
  408. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  409. .. function:: http_date(epoch_seconds=None)
  410. Formats the time to match the :rfc:`1123` date format as specified by HTTP
  411. :rfc:`2616#section-3.3.1` section 3.3.1.
  412. Accepts a floating point number expressed in seconds since the epoch in
  413. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  414. defaults to the current time.
  415. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  416. .. function:: base36_to_int(s)
  417. Converts a base 36 string to an integer. On Python 2 the output is
  418. guaranteed to be an ``int`` and not a ``long``.
  419. .. function:: int_to_base36(i)
  420. Converts a positive integer to a base 36 string. On Python 2 ``i`` must be
  421. smaller than :data:`sys.maxint`.
  422. ``django.utils.safestring``
  423. ===========================
  424. .. module:: django.utils.safestring
  425. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  426. Functions and classes for working with "safe strings": strings that can be
  427. displayed safely without further escaping in HTML. Marking something as a "safe
  428. string" means that the producer of the string has already turned characters
  429. that should not be interpreted by the HTML engine (e.g. '<') into the
  430. appropriate entities.
  431. .. class:: SafeBytes
  432. .. versionadded:: 1.5
  433. A ``bytes`` subclass that has been specifically marked as "safe"
  434. (requires no further escaping) for HTML output purposes.
  435. .. class:: SafeString
  436. A ``str`` subclass that has been specifically marked as "safe"
  437. (requires no further escaping) for HTML output purposes. This is
  438. :class:`SafeBytes` on Python 2 and :class:`SafeText` on Python 3.
  439. .. class:: SafeText
  440. .. versionadded:: 1.5
  441. A ``str`` (in Python 3) or ``unicode`` (in Python 2) subclass
  442. that has been specifically marked as "safe" for HTML output purposes.
  443. .. class:: SafeUnicode
  444. Historical name of :class:`SafeText`. Only available under Python 2.
  445. .. function:: mark_safe(s)
  446. Explicitly mark a string as safe for (HTML) output purposes. The returned
  447. object can be used everywhere a string or unicode object is appropriate.
  448. Can be called multiple times on a single string.
  449. .. function:: mark_for_escaping(s)
  450. Explicitly mark a string as requiring HTML escaping upon output. Has no
  451. effect on ``SafeData`` subclasses.
  452. Can be called multiple times on a single string (the resulting escaping is
  453. only applied once).
  454. ``django.utils.text``
  455. =====================
  456. .. module:: django.utils.text
  457. :synopsis: Text manipulation.
  458. .. function:: slugify
  459. Converts to lowercase, removes non-word characters (alphanumerics and
  460. underscores) and converts spaces to hyphens. Also strips leading and trailing
  461. whitespace.
  462. For example::
  463. slugify(value)
  464. If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
  465. ``django.utils.translation``
  466. ============================
  467. .. module:: django.utils.translation
  468. :synopsis: Internationalization support.
  469. For a complete discussion on the usage of the following see the
  470. :doc:`translation documentation </topics/i18n/translation>`.
  471. .. function:: gettext(message)
  472. Translates ``message`` and returns it in a UTF-8 bytestring
  473. .. function:: ugettext(message)
  474. Translates ``message`` and returns it in a unicode string
  475. .. function:: pgettext(context, message)
  476. Translates ``message`` given the ``context`` and returns
  477. it in a unicode string.
  478. For more information, see :ref:`contextual-markers`.
  479. .. function:: gettext_lazy(message)
  480. .. function:: ugettext_lazy(message)
  481. .. function:: pgettext_lazy(context, message)
  482. Same as the non-lazy versions above, but using lazy execution.
  483. See :ref:`lazy translations documentation <lazy-translations>`.
  484. .. function:: gettext_noop(message)
  485. .. function:: ugettext_noop(message)
  486. Marks strings for translation but doesn't translate them now. This can be
  487. used to store strings in global variables that should stay in the base
  488. language (because they might be used externally) and will be translated
  489. later.
  490. .. function:: ngettext(singular, plural, number)
  491. Translates ``singular`` and ``plural`` and returns the appropriate string
  492. based on ``number`` in a UTF-8 bytestring.
  493. .. function:: ungettext(singular, plural, number)
  494. Translates ``singular`` and ``plural`` and returns the appropriate string
  495. based on ``number`` in a unicode string.
  496. .. function:: npgettext(context, singular, plural, number)
  497. Translates ``singular`` and ``plural`` and returns the appropriate string
  498. based on ``number`` and the ``context`` in a unicode string.
  499. .. function:: ngettext_lazy(singular, plural, number)
  500. .. function:: ungettext_lazy(singular, plural, number)
  501. .. function:: npgettext_lazy(singular, plural, number)
  502. Same as the non-lazy versions above, but using lazy execution.
  503. See :ref:`lazy translations documentation <lazy-translations>`.
  504. .. function:: string_concat(*strings)
  505. Lazy variant of string concatenation, needed for translations that are
  506. constructed from multiple parts.
  507. .. function:: activate(language)
  508. Fetches the translation object for a given language and installs it as
  509. the current translation object for the current thread.
  510. .. function:: deactivate()
  511. De-installs the currently active translation object so that further _ calls
  512. will resolve against the default translation object, again.
  513. .. function:: deactivate_all()
  514. Makes the active translation object a NullTranslations() instance. This is
  515. useful when we want delayed translations to appear as the original string
  516. for some reason.
  517. .. function:: override(language, deactivate=False)
  518. A Python context manager that uses
  519. :func:`django.utils.translation.activate` to fetch the translation object
  520. for a given language, installing it as the translation object for the
  521. current thread and reinstall the previous active language on exit.
  522. Optionally it can simply deinstall the temporary translation on exit with
  523. :func:`django.utils.translation.deactivate` if the deactivate argument is
  524. True. If you pass None as the language argument, a NullTranslations()
  525. instance is installed while the context is active.
  526. .. function:: get_language()
  527. Returns the currently selected language code.
  528. .. function:: get_language_bidi()
  529. Returns selected language's BiDi layout:
  530. * ``False`` = left-to-right layout
  531. * ``True`` = right-to-left layout
  532. .. function:: get_language_from_request(request, check_path=False)
  533. Analyzes the request to find what language the user wants the system to show.
  534. Only languages listed in settings.LANGUAGES are taken into account. If the user
  535. requests a sublanguage where we have a main language, we send out the main
  536. language.
  537. If ``check_path`` is ``True``, the function first checks the requested URL
  538. for whether its path begins with a language code listed in the
  539. :setting:`LANGUAGES` setting.
  540. .. function:: to_locale(language)
  541. Turns a language name (en-us) into a locale name (en_US).
  542. .. function:: templatize(src)
  543. Turns a Django template into something that is understood by xgettext. It does
  544. so by translating the Django translation tags into standard gettext function
  545. invocations.
  546. .. _time-zone-selection-functions:
  547. ``django.utils.timezone``
  548. =========================
  549. .. module:: django.utils.timezone
  550. :synopsis: Timezone support.
  551. .. data:: utc
  552. :class:`~datetime.tzinfo` instance that represents UTC.
  553. .. function:: get_default_timezone()
  554. Returns a :class:`~datetime.tzinfo` instance that represents the
  555. :ref:`default time zone <default-current-time-zone>`.
  556. .. function:: get_default_timezone_name()
  557. Returns the name of the :ref:`default time zone
  558. <default-current-time-zone>`.
  559. .. function:: get_current_timezone()
  560. Returns a :class:`~datetime.tzinfo` instance that represents the
  561. :ref:`current time zone <default-current-time-zone>`.
  562. .. function:: get_current_timezone_name()
  563. Returns the name of the :ref:`current time zone
  564. <default-current-time-zone>`.
  565. .. function:: activate(timezone)
  566. Sets the :ref:`current time zone <default-current-time-zone>`. The
  567. ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
  568. subclass or, if pytz_ is available, a time zone name.
  569. .. function:: deactivate()
  570. Unsets the :ref:`current time zone <default-current-time-zone>`.
  571. .. function:: override(timezone)
  572. This is a Python context manager that sets the :ref:`current time zone
  573. <default-current-time-zone>` on entry with :func:`activate()`, and restores
  574. the previously active time zone on exit. If the ``timezone`` argument is
  575. ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
  576. on entry with :func:`deactivate()` instead.
  577. .. versionadded:: 1.5
  578. .. function:: localtime(value, timezone=None)
  579. Converts an aware :class:`~datetime.datetime` to a different time zone,
  580. by default the :ref:`current time zone <default-current-time-zone>`.
  581. This function doesn't work on naive datetimes; use :func:`make_aware`
  582. instead.
  583. .. function:: now()
  584. Returns an aware or naive :class:`~datetime.datetime` that represents the
  585. current point in time when :setting:`USE_TZ` is ``True`` or ``False``
  586. respectively.
  587. .. function:: is_aware(value)
  588. Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
  589. function assumes that ``value`` is a :class:`~datetime.datetime`.
  590. .. function:: is_naive(value)
  591. Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
  592. function assumes that ``value`` is a :class:`~datetime.datetime`.
  593. .. function:: make_aware(value, timezone)
  594. Returns an aware :class:`~datetime.datetime` that represents the same
  595. point in time as ``value`` in ``timezone``, ``value`` being a naive
  596. :class:`~datetime.datetime`.
  597. This function can raise an exception if ``value`` doesn't exist or is
  598. ambiguous because of DST transitions.
  599. .. function:: make_naive(value, timezone)
  600. Returns an naive :class:`~datetime.datetime` that represents in
  601. ``timezone`` the same point in time as ``value``, ``value`` being an
  602. aware :class:`~datetime.datetime`
  603. .. _pytz: http://pytz.sourceforge.net/
  604. ``django.utils.tzinfo``
  605. =======================
  606. .. module:: django.utils.tzinfo
  607. :synopsis: Implementation of ``tzinfo`` classes for use with ``datetime.datetime``.
  608. .. class:: FixedOffset
  609. Fixed offset in minutes east from UTC.
  610. .. class:: LocalTimezone
  611. Proxy timezone information from time module.