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