utils.txt 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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
  25. need 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 a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate``
  49. header to a response to indicate that a page should never be cached.
  50. .. versionchanged:: 1.9
  51. Before Django 1.9, ``Cache-Control: max-age=0`` was sent. This didn't
  52. reliably prevent caching in all browsers.
  53. .. function:: patch_vary_headers(response, newheaders)
  54. Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
  55. ``newheaders`` is a list of header names that should be in ``Vary``.
  56. Existing headers in ``Vary`` aren't removed.
  57. .. function:: get_cache_key(request, key_prefix=None)
  58. Returns a cache key based on the request path. It can be used in the
  59. request phase because it pulls the list of headers to take into account
  60. from the global path registry and uses those to build a cache key to
  61. check against.
  62. If there is no headerlist stored, the page needs to be rebuilt, so this
  63. function returns ``None``.
  64. .. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None)
  65. Learns what headers to take into account for some request path from the
  66. response object. It stores those headers in a global path registry so that
  67. later access to that path will know what headers to take into account
  68. without building the response object itself. The headers are named in
  69. the ``Vary`` header of the response, but we want to prevent response
  70. generation.
  71. The list of headers to use for cache key generation is stored in the same
  72. cache as the pages themselves. If the cache ages some data out of the
  73. cache, this just means that we have to build the response once to get at
  74. the Vary header and so at the list of headers to use for the cache key.
  75. ``django.utils.dateparse``
  76. ==========================
  77. .. module:: django.utils.dateparse
  78. :synopsis: Functions to parse datetime objects.
  79. The functions defined in this module share the following properties:
  80. - They raise :exc:`ValueError` if their input is well formatted but isn't a
  81. valid date or time.
  82. - They return ``None`` if it isn't well formatted at all.
  83. - They accept up to picosecond resolution in input, but they truncate it to
  84. microseconds, since that's what Python supports.
  85. .. function:: parse_date(value)
  86. Parses a string and returns a :class:`datetime.date`.
  87. .. function:: parse_time(value)
  88. Parses a string and returns a :class:`datetime.time`.
  89. UTC offsets aren't supported; if ``value`` describes one, the result is
  90. ``None``.
  91. .. function:: parse_datetime(value)
  92. Parses a string and returns a :class:`datetime.datetime`.
  93. UTC offsets are supported; if ``value`` describes one, the result's
  94. ``tzinfo`` attribute is a :class:`~django.utils.timezone.FixedOffset`
  95. instance.
  96. .. function:: parse_duration(value)
  97. Parses a string and returns a :class:`datetime.timedelta`.
  98. Expects data in the format ``"DD HH:MM:SS.uuuuuu"`` or as specified by ISO
  99. 8601 (e.g. ``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``).
  100. ``django.utils.decorators``
  101. ===========================
  102. .. module:: django.utils.decorators
  103. :synopsis: Functions that help with creating decorators for views.
  104. .. function:: method_decorator(decorator, name='')
  105. Converts a function decorator into a method decorator. It can be used to
  106. decorate methods or classes; in the latter case, ``name`` is the name
  107. of the method to be decorated and is required.
  108. ``decorator`` may also be a a list or tuple of functions. They are wrapped
  109. in reverse order so that the call order is the order in which the functions
  110. appear in the list/tuple.
  111. See :ref:`decorating class based views <decorating-class-based-views>` for
  112. example usage.
  113. .. versionchanged:: 1.9
  114. The ability to decorate classes, the ``name`` parameter, and the ability
  115. for ``decorator`` to accept a list/tuple of decorator functions were
  116. added.
  117. .. function:: decorator_from_middleware(middleware_class)
  118. Given a middleware class, returns a view decorator. This lets you use
  119. middleware functionality on a per-view basis. The middleware is created
  120. with no params passed.
  121. .. function:: decorator_from_middleware_with_args(middleware_class)
  122. Like ``decorator_from_middleware``, but returns a function
  123. that accepts the arguments to be passed to the middleware_class.
  124. For example, the :func:`~django.views.decorators.cache.cache_page`
  125. decorator is created from the ``CacheMiddleware`` like this::
  126. cache_page = decorator_from_middleware_with_args(CacheMiddleware)
  127. @cache_page(3600)
  128. def my_view(request):
  129. pass
  130. ``django.utils.encoding``
  131. =========================
  132. .. module:: django.utils.encoding
  133. :synopsis: A series of helper functions to manage character encoding.
  134. .. function:: python_2_unicode_compatible
  135. A decorator that defines ``__unicode__`` and ``__str__`` methods under
  136. Python 2. Under Python 3 it does nothing.
  137. To support Python 2 and 3 with a single code base, define a ``__str__``
  138. method returning text and apply this decorator to the class.
  139. .. function:: smart_text(s, encoding='utf-8', strings_only=False, errors='strict')
  140. Returns a text object representing ``s`` -- ``unicode`` on Python 2 and
  141. ``str`` on Python 3. Treats bytestrings using the ``encoding`` codec.
  142. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  143. objects.
  144. .. function:: smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  145. Historical name of :func:`smart_text`. Only available under Python 2.
  146. .. function:: is_protected_type(obj)
  147. Determine if the object instance is of a protected type.
  148. Objects of protected types are preserved as-is when passed to
  149. ``force_text(strings_only=True)``.
  150. .. function:: force_text(s, encoding='utf-8', strings_only=False, errors='strict')
  151. Similar to ``smart_text``, except that lazy instances are resolved to
  152. strings, rather than kept as lazy objects.
  153. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  154. objects.
  155. .. function:: force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')
  156. Historical name of :func:`force_text`. Only available under Python 2.
  157. .. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  158. Returns a bytestring version of ``s``, encoded as specified in
  159. ``encoding``.
  160. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  161. objects.
  162. .. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')
  163. Similar to ``smart_bytes``, except that lazy instances are resolved to
  164. bytestrings, rather than kept as lazy objects.
  165. If ``strings_only`` is ``True``, don't convert (some) non-string-like
  166. objects.
  167. .. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')
  168. Alias of :func:`smart_bytes` on Python 2 and :func:`smart_text` on Python
  169. 3. This function returns a ``str`` or a lazy string.
  170. For instance, this is suitable for writing to :data:`sys.stdout` on
  171. Python 2 and 3.
  172. .. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')
  173. Alias of :func:`force_bytes` on Python 2 and :func:`force_text` on Python
  174. 3. This function always returns a ``str``.
  175. .. function:: iri_to_uri(iri)
  176. Convert an Internationalized Resource Identifier (IRI) portion to a URI
  177. portion that is suitable for inclusion in a URL.
  178. This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`. However,
  179. since we are assuming input is either UTF-8 or unicode already, we can
  180. simplify things a little from the full method.
  181. Takes an IRI in UTF-8 bytes and returns ASCII bytes containing the encoded
  182. result.
  183. .. function:: uri_to_iri(uri)
  184. Converts a Uniform Resource Identifier into an Internationalized Resource
  185. Identifier.
  186. This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`.
  187. Takes a URI in ASCII bytes and returns a unicode string containing the
  188. encoded result.
  189. .. function:: filepath_to_uri(path)
  190. Convert a file system path to a URI portion that is suitable for inclusion
  191. in a URL. The path is assumed to be either UTF-8 or unicode.
  192. This method will encode certain characters that would normally be
  193. recognized as special characters for URIs. Note that this method does not
  194. encode the ' character, as it is a valid character within URIs. See
  195. ``encodeURIComponent()`` JavaScript function for more details.
  196. Returns an ASCII string containing the encoded result.
  197. .. function:: escape_uri_path(path)
  198. Escapes the unsafe characters from the path portion of a Uniform Resource
  199. Identifier (URI).
  200. ``django.utils.feedgenerator``
  201. ==============================
  202. .. module:: django.utils.feedgenerator
  203. :synopsis: Syndication feed generation library -- used for generating RSS, etc.
  204. Sample usage::
  205. >>> from django.utils import feedgenerator
  206. >>> feed = feedgenerator.Rss201rev2Feed(
  207. ... title="Poynter E-Media Tidbits",
  208. ... link="http://www.poynter.org/column.asp?id=31",
  209. ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
  210. ... language="en",
  211. ... )
  212. >>> feed.add_item(
  213. ... title="Hello",
  214. ... link="http://www.holovaty.com/test/",
  215. ... description="Testing."
  216. ... )
  217. >>> with open('test.rss', 'w') as fp:
  218. ... feed.write(fp, 'utf-8')
  219. For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
  220. which is currently ``Rss201rev2Feed``
  221. For definitions of the different versions of RSS, see:
  222. https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  223. .. function:: get_tag_uri(url, date)
  224. Creates a TagURI.
  225. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  226. SyndicationFeed
  227. ---------------
  228. .. class:: SyndicationFeed
  229. Base class for all syndication feeds. Subclasses should provide write().
  230. .. 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)
  231. Initialize the feed with the given dictionary of metadata, which applies
  232. to the entire feed.
  233. Any extra keyword arguments you pass to ``__init__`` will be stored in
  234. ``self.feed``.
  235. All parameters should be Unicode objects, except ``categories``, which
  236. should be a sequence of Unicode objects.
  237. .. 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, updateddate=None, enclosures=None, **kwargs)
  238. Adds an item to the feed. All args are expected to be Python ``unicode``
  239. objects except ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
  240. objects, ``enclosure``, which is an ``Enclosure`` instance, and
  241. ``enclosures``, which is a list of ``Enclosure`` instances.
  242. .. deprecated:: 1.9
  243. The ``enclosure`` keyword argument is deprecated in favor of the
  244. new ``enclosures`` keyword argument which accepts a list of
  245. ``Enclosure`` objects.
  246. .. method:: num_items()
  247. .. method:: root_attributes()
  248. Return extra attributes to place on the root (i.e. feed/channel)
  249. element. Called from ``write()``.
  250. .. method:: add_root_elements(handler)
  251. Add elements in the root (i.e. feed/channel) element.
  252. Called from ``write()``.
  253. .. method:: item_attributes(item)
  254. Return extra attributes to place on each item (i.e. item/entry)
  255. element.
  256. .. method:: add_item_elements(handler, item)
  257. Add elements on each item (i.e. item/entry) element.
  258. .. method:: write(outfile, encoding)
  259. Outputs the feed in the given encoding to ``outfile``, which is a
  260. file-like object. Subclasses should override this.
  261. .. method:: writeString(encoding)
  262. Returns the feed in the given encoding as a string.
  263. .. method:: latest_post_date()
  264. Returns the latest ``pubdate`` or ``updateddate`` for all items in the
  265. feed. If no items have either of these attributes this returns the
  266. 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: https://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: https://tools.ietf.org/html/rfc4287
  286. ``django.utils.functional``
  287. ===========================
  288. .. module:: django.utils.functional
  289. :synopsis: Functional programming tools.
  290. .. class:: cached_property(object, name)
  291. The ``@cached_property`` decorator caches the result of a method with a
  292. single ``self`` argument as a property. The cached result will persist
  293. as long as the instance does, so if the instance is passed around and the
  294. function subsequently invoked, the cached result will be returned.
  295. Consider a typical case, where a view might need to call a model's method
  296. to perform some computation, before placing the model instance into the
  297. context, where the template might invoke the method once more::
  298. # the model
  299. class Person(models.Model):
  300. def friends(self):
  301. # expensive computation
  302. ...
  303. return friends
  304. # in the view:
  305. if person.friends():
  306. ...
  307. And in the template you would have:
  308. .. code-block:: html+django
  309. {% for friend in person.friends %}
  310. Here, ``friends()`` will be called twice. Since the instance ``person`` in
  311. the view and the template are the same, ``@cached_property`` can avoid
  312. that::
  313. from django.utils.functional import cached_property
  314. @cached_property
  315. def friends(self):
  316. # expensive computation
  317. ...
  318. return friends
  319. Note that as the method is now a property, in Python code it will need to
  320. be invoked appropriately::
  321. # in the view:
  322. if person.friends:
  323. ...
  324. The cached value can be treated like an ordinary attribute of the instance::
  325. # clear it, requiring re-computation next time it's called
  326. del person.friends # or delattr(person, "friends")
  327. # set a value manually, that will persist on the instance until cleared
  328. person.friends = ["Huckleberry Finn", "Tom Sawyer"]
  329. As well as offering potential performance advantages, ``@cached_property``
  330. can ensure that an attribute's value does not change unexpectedly over the
  331. life of an instance. This could occur with a method whose computation is
  332. based on ``datetime.now()``, or simply if a change were saved to the
  333. database by some other process in the brief interval between subsequent
  334. invocations of a method on the same instance.
  335. You can use the ``name`` argument to make cached properties of other
  336. methods. For example, if you had an expensive ``get_friends()`` method and
  337. wanted to allow calling it without retrieving the cached value, you could
  338. write::
  339. friends = cached_property(get_friends, name='friends')
  340. While ``person.get_friends()`` will recompute the friends on each call, the
  341. value of the cached property will persist until you delete it as described
  342. above::
  343. x = person.friends # calls first time
  344. y = person.get_friends() # calls again
  345. z = person.friends # does not call
  346. x is z # is True
  347. .. function:: allow_lazy(func, *resultclasses)
  348. .. deprecated:: 1.10
  349. Works like :meth:`~django.utils.functional.keep_lazy` except that it can't
  350. be used as a decorator.
  351. .. function:: keep_lazy(func, *resultclasses)
  352. .. versionadded:: 1.10
  353. Django offers many utility functions (particularly in ``django.utils``)
  354. that take a string as their first argument and do something to that string.
  355. These functions are used by template filters as well as directly in other
  356. code.
  357. If you write your own similar functions and deal with translations, you'll
  358. face the problem of what to do when the first argument is a lazy
  359. translation object. You don't want to convert it to a string immediately,
  360. because you might be using this function outside of a view (and hence the
  361. current thread's locale setting will not be correct).
  362. For cases like this, use the ``django.utils.functional.keep_lazy()``
  363. decorator. It modifies the function so that *if* it's called with a lazy
  364. translation as one of its arguments, the function evaluation is delayed
  365. until it needs to be converted to a string.
  366. For example::
  367. from django.utils import six
  368. from django.utils.functional import keep_lazy, keep_lazy_text
  369. def fancy_utility_function(s, ...):
  370. # Do some conversion on string 's'
  371. ...
  372. fancy_utility_function = keep_lazy(six.text_type)(fancy_utility_function)
  373. # Or more succinctly:
  374. @keep_lazy(six.text_type)
  375. def fancy_utility_function(s, ...):
  376. ...
  377. The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``)
  378. specifying the type(s) that the original function can return. A common
  379. use case is to have functions that return text. For these, you can just
  380. pass the ``six.text_type`` type to ``keep_lazy`` (or even simpler, use the
  381. :func:`keep_lazy_text` decorator described in the next section).
  382. Using this decorator means you can write your function and assume that the
  383. input is a proper string, then add support for lazy translation objects at
  384. the end.
  385. .. function:: keep_lazy_text(func)
  386. .. versionadded:: 1.10
  387. A shortcut for ``keep_lazy(six.text_type)(func)``.
  388. If you have a function that returns text and you want to be able to take
  389. lazy arguments while delaying their evaluation, simply use this decorator::
  390. from django.utils import six
  391. from django.utils.functional import keep_lazy, keep_lazy_text
  392. # Our previous example was:
  393. @keep_lazy(six.text_type)
  394. def fancy_utility_function(s, ...):
  395. ...
  396. # Which can be rewritten as:
  397. @keep_lazy_text
  398. def fancy_utility_function(s, ...):
  399. ...
  400. ``django.utils.html``
  401. =====================
  402. .. module:: django.utils.html
  403. :synopsis: HTML helper functions
  404. Usually you should build up HTML using Django's templates to make use of its
  405. autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
  406. where appropriate. This module provides some additional low level utilities for
  407. escaping HTML.
  408. .. function:: escape(text)
  409. Returns the given text with ampersands, quotes and angle brackets encoded
  410. for use in HTML. The input is first passed through
  411. :func:`~django.utils.encoding.force_text` and the output has
  412. :func:`~django.utils.safestring.mark_safe` applied.
  413. .. function:: conditional_escape(text)
  414. Similar to ``escape()``, except that it doesn't operate on pre-escaped
  415. strings, so it will not double escape.
  416. .. function:: format_html(format_string, *args, **kwargs)
  417. This is similar to `str.format`_, except that it is appropriate for
  418. building up HTML fragments. All args and kwargs are passed through
  419. :func:`conditional_escape` before being passed to ``str.format``.
  420. For the case of building up small HTML fragments, this function is to be
  421. preferred over string interpolation using ``%`` or ``str.format`` directly,
  422. because it applies escaping to all arguments - just like the Template system
  423. applies escaping by default.
  424. So, instead of writing::
  425. mark_safe("%s <b>%s</b> %s" % (some_html,
  426. escape(some_text),
  427. escape(some_other_text),
  428. ))
  429. You should instead use::
  430. format_html("{} <b>{}</b> {}",
  431. mark_safe(some_html), some_text, some_other_text)
  432. This has the advantage that you don't need to apply :func:`escape` to each
  433. argument and risk a bug and an XSS vulnerability if you forget one.
  434. Note that although this function uses ``str.format`` to do the
  435. interpolation, some of the formatting options provided by `str.format`_
  436. (e.g. number formatting) will not work, since all arguments are passed
  437. through :func:`conditional_escape` which (ultimately) calls
  438. :func:`~django.utils.encoding.force_text` on the values.
  439. .. _str.format: https://docs.python.org/library/stdtypes.html#str.format
  440. .. function:: format_html_join(sep, format_string, args_generator)
  441. A wrapper of :func:`format_html`, for the common case of a group of
  442. arguments that need to be formatted using the same format string, and then
  443. joined using ``sep``. ``sep`` is also passed through
  444. :func:`conditional_escape`.
  445. ``args_generator`` should be an iterator that returns the sequence of
  446. ``args`` that will be passed to :func:`format_html`. For example::
  447. format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
  448. for u in users))
  449. .. function:: strip_tags(value)
  450. Tries to remove anything that looks like an HTML tag from the string, that
  451. is anything contained within ``<>``.
  452. Absolutely NO guarantee is provided about the resulting string being
  453. HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
  454. escaping it first, for example with :func:`~django.utils.html.escape`.
  455. For example::
  456. strip_tags(value)
  457. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
  458. the return value will be ``"Joel is a slug"``.
  459. If you are looking for a more robust solution, take a look at the `bleach
  460. <https://pypi.python.org/pypi/bleach>`_ Python library.
  461. .. function:: html_safe()
  462. The ``__html__()`` method on a class helps non-Django templates detect
  463. classes whose output doesn't require HTML escaping.
  464. This decorator defines the ``__html__()`` method on the decorated class
  465. by wrapping the ``__unicode__()`` (Python 2) or ``__str__()`` (Python 3)
  466. in :meth:`~django.utils.safestring.mark_safe`. Ensure the ``__unicode__()``
  467. or ``__str__()`` method does indeed return text that doesn't require HTML
  468. escaping.
  469. ``django.utils.http``
  470. =====================
  471. .. module:: django.utils.http
  472. :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)
  473. .. function:: urlquote(url, safe='/')
  474. A version of Python's ``urllib.quote()`` function that can operate on
  475. unicode strings. The url is first UTF-8 encoded before quoting. The
  476. returned string can safely be used as part of an argument to a subsequent
  477. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  478. execution.
  479. .. function:: urlquote_plus(url, safe='')
  480. A version of Python's urllib.quote_plus() function that can operate on
  481. unicode strings. The url is first UTF-8 encoded before quoting. The
  482. returned string can safely be used as part of an argument to a subsequent
  483. ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
  484. execution.
  485. .. function:: urlencode(query, doseq=0)
  486. A version of Python's urllib.urlencode() function that can operate on
  487. unicode strings. The parameters are first cast to UTF-8 encoded strings
  488. and then encoded as per normal.
  489. .. function:: cookie_date(epoch_seconds=None)
  490. Formats the time to ensure compatibility with Netscape's cookie standard.
  491. Accepts a floating point number expressed in seconds since the epoch in
  492. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  493. defaults to the current time.
  494. Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.
  495. .. function:: http_date(epoch_seconds=None)
  496. Formats the time to match the :rfc:`1123` date format as specified by HTTP
  497. :rfc:`2616#section-3.3.1` section 3.3.1.
  498. Accepts a floating point number expressed in seconds since the epoch in
  499. UTC--such as that outputted by ``time.time()``. If set to ``None``,
  500. defaults to the current time.
  501. Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.
  502. .. function:: base36_to_int(s)
  503. Converts a base 36 string to an integer. On Python 2 the output is
  504. guaranteed to be an ``int`` and not a ``long``.
  505. .. function:: int_to_base36(i)
  506. Converts a positive integer to a base 36 string. On Python 2 ``i`` must be
  507. smaller than `sys.maxint`_.
  508. .. _sys.maxint: https://docs.python.org/2/library/sys.html#sys.maxint
  509. .. function:: urlsafe_base64_encode(s)
  510. Encodes a bytestring in base64 for use in URLs, stripping any trailing
  511. equal signs.
  512. .. function:: urlsafe_base64_decode(s)
  513. Decodes a base64 encoded string, adding back any trailing equal signs that
  514. might have been stripped.
  515. ``django.utils.module_loading``
  516. ===============================
  517. .. module:: django.utils.module_loading
  518. :synopsis: Functions for working with Python modules.
  519. Functions for working with Python modules.
  520. .. function:: import_string(dotted_path)
  521. Imports a dotted module path and returns the attribute/class designated by
  522. the last name in the path. Raises ``ImportError`` if the import failed. For
  523. example::
  524. from django.utils.module_loading import import_string
  525. ValidationError = import_string('django.core.exceptions.ValidationError')
  526. is equivalent to::
  527. from django.core.exceptions import ValidationError
  528. ``django.utils.safestring``
  529. ===========================
  530. .. module:: django.utils.safestring
  531. :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.
  532. Functions and classes for working with "safe strings": strings that can be
  533. displayed safely without further escaping in HTML. Marking something as a "safe
  534. string" means that the producer of the string has already turned characters
  535. that should not be interpreted by the HTML engine (e.g. '<') into the
  536. appropriate entities.
  537. .. class:: SafeBytes
  538. A ``bytes`` subclass that has been specifically marked as "safe"
  539. (requires no further escaping) for HTML output purposes.
  540. .. class:: SafeString
  541. A ``str`` subclass that has been specifically marked as "safe"
  542. (requires no further escaping) for HTML output purposes. This is
  543. :class:`SafeBytes` on Python 2 and :class:`SafeText` on Python 3.
  544. .. class:: SafeText
  545. A ``str`` (in Python 3) or ``unicode`` (in Python 2) subclass
  546. that has been specifically marked as "safe" for HTML output purposes.
  547. .. class:: SafeUnicode
  548. Historical name of :class:`SafeText`. Only available under Python 2.
  549. .. function:: mark_safe(s)
  550. Explicitly mark a string as safe for (HTML) output purposes. The returned
  551. object can be used everywhere a string or unicode object is appropriate.
  552. Can be called multiple times on a single string.
  553. For building up fragments of HTML, you should normally be using
  554. :func:`django.utils.html.format_html` instead.
  555. String marked safe will become unsafe again if modified. For example::
  556. >>> mystr = '<b>Hello World</b> '
  557. >>> mystr = mark_safe(mystr)
  558. >>> type(mystr)
  559. <class 'django.utils.safestring.SafeBytes'>
  560. >>> mystr = mystr.strip() # removing whitespace
  561. >>> type(mystr)
  562. <type 'str'>
  563. .. function:: mark_for_escaping(s)
  564. Explicitly mark a string as requiring HTML escaping upon output. Has no
  565. effect on ``SafeData`` subclasses.
  566. Can be called multiple times on a single string (the resulting escaping is
  567. only applied once).
  568. ``django.utils.text``
  569. =====================
  570. .. module:: django.utils.text
  571. :synopsis: Text manipulation.
  572. .. function:: slugify(allow_unicode=False)
  573. Converts to ASCII if ``allow_unicode`` is ``False`` (default). Converts spaces to
  574. hyphens. Removes characters that aren't alphanumerics, underscores, or
  575. hyphens. Converts to lowercase. Also strips leading and trailing whitespace.
  576. For example::
  577. slugify(value)
  578. If ``value`` is ``"Joel is a slug"``, the output will be
  579. ``"joel-is-a-slug"``.
  580. You can set the ``allow_unicode`` parameter to ``True``, if you want to
  581. allow Unicode characters::
  582. slugify(value, allow_unicode=True)
  583. If ``value`` is ``"你好 World"``, the output will be ``"你好-world"``.
  584. .. versionchanged:: 1.9
  585. The ``allow_unicode`` parameter was added.
  586. .. _time-zone-selection-functions:
  587. ``django.utils.timezone``
  588. =========================
  589. .. module:: django.utils.timezone
  590. :synopsis: Timezone support.
  591. .. data:: utc
  592. :class:`~datetime.tzinfo` instance that represents UTC.
  593. .. class:: FixedOffset(offset=None, name=None)
  594. A :class:`~datetime.tzinfo` subclass modeling a fixed offset from UTC.
  595. ``offset`` is an integer number of minutes east of UTC.
  596. .. function:: get_fixed_timezone(offset)
  597. Returns a :class:`~datetime.tzinfo` instance that represents a time zone
  598. with a fixed offset from UTC.
  599. ``offset`` is a :class:`datetime.timedelta` or an integer number of
  600. minutes. Use positive values for time zones east of UTC and negative
  601. values for west of UTC.
  602. .. function:: get_default_timezone()
  603. Returns a :class:`~datetime.tzinfo` instance that represents the
  604. :ref:`default time zone <default-current-time-zone>`.
  605. .. function:: get_default_timezone_name()
  606. Returns the name of the :ref:`default time zone
  607. <default-current-time-zone>`.
  608. .. function:: get_current_timezone()
  609. Returns a :class:`~datetime.tzinfo` instance that represents the
  610. :ref:`current time zone <default-current-time-zone>`.
  611. .. function:: get_current_timezone_name()
  612. Returns the name of the :ref:`current time zone
  613. <default-current-time-zone>`.
  614. .. function:: activate(timezone)
  615. Sets the :ref:`current time zone <default-current-time-zone>`. The
  616. ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
  617. subclass or, if pytz_ is available, a time zone name.
  618. .. function:: deactivate()
  619. Unsets the :ref:`current time zone <default-current-time-zone>`.
  620. .. function:: override(timezone)
  621. This is a Python context manager that sets the :ref:`current time zone
  622. <default-current-time-zone>` on entry with :func:`activate()`, and restores
  623. the previously active time zone on exit. If the ``timezone`` argument is
  624. ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
  625. on entry with :func:`deactivate()` instead.
  626. ``override`` is also usable as a function decorator.
  627. .. function:: localtime(value, timezone=None)
  628. Converts an aware :class:`~datetime.datetime` to a different time zone,
  629. by default the :ref:`current time zone <default-current-time-zone>`.
  630. This function doesn't work on naive datetimes; use :func:`make_aware`
  631. instead.
  632. .. function:: now()
  633. Returns a :class:`~datetime.datetime` that represents the
  634. current point in time. Exactly what's returned depends on the value of
  635. :setting:`USE_TZ`:
  636. * If :setting:`USE_TZ` is ``False``, this will be a
  637. :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
  638. without an associated timezone) that represents the current time
  639. in the system's local timezone.
  640. * If :setting:`USE_TZ` is ``True``, this will be an
  641. :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
  642. current time in UTC. Note that :func:`now` will always return
  643. times in UTC regardless of the value of :setting:`TIME_ZONE`;
  644. you can use :func:`localtime` to convert to a time in the current
  645. time zone.
  646. .. function:: is_aware(value)
  647. Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
  648. function assumes that ``value`` is a :class:`~datetime.datetime`.
  649. .. function:: is_naive(value)
  650. Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
  651. function assumes that ``value`` is a :class:`~datetime.datetime`.
  652. .. function:: make_aware(value, timezone=None, is_dst=None)
  653. Returns an aware :class:`~datetime.datetime` that represents the same
  654. point in time as ``value`` in ``timezone``, ``value`` being a naive
  655. :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  656. defaults to the :ref:`current time zone <default-current-time-zone>`.
  657. When pytz_ is installed, the exception ``pytz.AmbiguousTimeError``
  658. will be raised if you try to make ``value`` aware during a DST transition
  659. where the same time occurs twice (when reverting from DST). Setting
  660. ``is_dst`` to ``True`` or ``False`` will avoid the exception by choosing if
  661. the time is pre-transition or post-transition respectively.
  662. When pytz_ is installed, the exception ``pytz.NonExistentTimeError``
  663. will be raised if you try to make ``value`` aware during a DST transition
  664. such that the time never occurred (when entering into DST). Setting
  665. ``is_dst`` to ``True`` or ``False`` will avoid the exception by moving the
  666. hour backwards or forwards by 1 respectively. For example, ``is_dst=True``
  667. would change a non-existent time of 2:30 to 1:30 and ``is_dst=False``
  668. would change the time to 3:30.
  669. ``is_dst`` has no effect when ``pytz`` is not installed.
  670. .. versionchanged:: 1.9
  671. The ``is_dst`` argument was added.
  672. .. function:: make_naive(value, timezone=None)
  673. Returns an naive :class:`~datetime.datetime` that represents in
  674. ``timezone`` the same point in time as ``value``, ``value`` being an
  675. aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
  676. defaults to the :ref:`current time zone <default-current-time-zone>`.
  677. .. _pytz: http://pytz.sourceforge.net/
  678. ``django.utils.translation``
  679. ============================
  680. .. module:: django.utils.translation
  681. :synopsis: Internationalization support.
  682. For a complete discussion on the usage of the following see the
  683. :doc:`translation documentation </topics/i18n/translation>`.
  684. .. function:: gettext(message)
  685. Translates ``message`` and returns it in a UTF-8 bytestring
  686. .. function:: ugettext(message)
  687. Translates ``message`` and returns it in a unicode string
  688. .. function:: pgettext(context, message)
  689. Translates ``message`` given the ``context`` and returns
  690. it in a unicode string.
  691. For more information, see :ref:`contextual-markers`.
  692. .. function:: gettext_lazy(message)
  693. .. function:: ugettext_lazy(message)
  694. .. function:: pgettext_lazy(context, message)
  695. Same as the non-lazy versions above, but using lazy execution.
  696. See :ref:`lazy translations documentation <lazy-translations>`.
  697. .. function:: gettext_noop(message)
  698. .. function:: ugettext_noop(message)
  699. Marks strings for translation but doesn't translate them now. This can be
  700. used to store strings in global variables that should stay in the base
  701. language (because they might be used externally) and will be translated
  702. later.
  703. .. function:: ngettext(singular, plural, number)
  704. Translates ``singular`` and ``plural`` and returns the appropriate string
  705. based on ``number`` in a UTF-8 bytestring.
  706. .. function:: ungettext(singular, plural, number)
  707. Translates ``singular`` and ``plural`` and returns the appropriate string
  708. based on ``number`` in a unicode string.
  709. .. function:: npgettext(context, singular, plural, number)
  710. Translates ``singular`` and ``plural`` and returns the appropriate string
  711. based on ``number`` and the ``context`` in a unicode string.
  712. .. function:: ngettext_lazy(singular, plural, number)
  713. .. function:: ungettext_lazy(singular, plural, number)
  714. .. function:: npgettext_lazy(context, singular, plural, number)
  715. Same as the non-lazy versions above, but using lazy execution.
  716. See :ref:`lazy translations documentation <lazy-translations>`.
  717. .. function:: string_concat(*strings)
  718. Lazy variant of string concatenation, needed for translations that are
  719. constructed from multiple parts.
  720. .. function:: activate(language)
  721. Fetches the translation object for a given language and activates it as
  722. the current translation object for the current thread.
  723. .. function:: deactivate()
  724. Deactivates the currently active translation object so that further _ calls
  725. will resolve against the default translation object, again.
  726. .. function:: deactivate_all()
  727. Makes the active translation object a ``NullTranslations()`` instance.
  728. This is useful when we want delayed translations to appear as the original
  729. string for some reason.
  730. .. function:: override(language, deactivate=False)
  731. A Python context manager that uses
  732. :func:`django.utils.translation.activate` to fetch the translation object
  733. for a given language, activates it as the translation object for the
  734. current thread and reactivates the previous active language on exit.
  735. Optionally, it can simply deactivate the temporary translation on exit with
  736. :func:`django.utils.translation.deactivate` if the ``deactivate`` argument
  737. is ``True``. If you pass ``None`` as the language argument, a
  738. ``NullTranslations()`` instance is activated within the context.
  739. ``override`` is also usable as a function decorator.
  740. .. function:: check_for_language(lang_code)
  741. Checks whether there is a global language file for the given language
  742. code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
  743. language is available.
  744. .. function:: get_language()
  745. Returns the currently selected language code. Returns ``None`` if
  746. translations are temporarily deactivated (by :func:`deactivate_all()` or
  747. when ``None`` is passed to :func:`override()`).
  748. .. function:: get_language_bidi()
  749. Returns selected language's BiDi layout:
  750. * ``False`` = left-to-right layout
  751. * ``True`` = right-to-left layout
  752. .. function:: get_language_from_request(request, check_path=False)
  753. Analyzes the request to find what language the user wants the system to
  754. show. Only languages listed in settings.LANGUAGES are taken into account.
  755. If the user requests a sublanguage where we have a main language, we send
  756. out the main language.
  757. If ``check_path`` is ``True``, the function first checks the requested URL
  758. for whether its path begins with a language code listed in the
  759. :setting:`LANGUAGES` setting.
  760. .. function:: to_locale(language)
  761. Turns a language name (en-us) into a locale name (en_US).
  762. .. function:: templatize(src)
  763. Turns a Django template into something that is understood by ``xgettext``.
  764. It does so by translating the Django translation tags into standard
  765. ``gettext`` function invocations.
  766. .. data:: LANGUAGE_SESSION_KEY
  767. Session key under which the active language for the current session is
  768. stored.