PageRenderTime 221ms CodeModel.GetById 101ms app.highlight 4ms RepoModel.GetById 96ms app.codeStats 11ms

/docs/ref/utils.txt

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