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