Ticket #3469: 3469.diff

File 3469.diff, 17.1 KB (added by Ramiro Morales, 14 years ago)

Rupe's patch with some reST fixes and tweaks. Great work!

  • docs/misc/api-stability.txt

    diff --git a/docs/misc/api-stability.txt b/docs/misc/api-stability.txt
    a b  
    9696``django.utils``
    9797----------------
    9898
    99 Most of the modules in ``django.utils`` are designed for internal use. Only the following parts of ``django.utils`` can be considered stable:
     99Most of the modules in ``django.utils`` are designed for internal use. Only the following parts of :ref:`django.utils <ref-utils>` can be considered stable:
    100100
    101101    - ``django.utils.cache``
    102102    - ``django.utils.datastructures.SortedDict`` -- only this single class; the
  • docs/ref/index.txt

    diff --git a/docs/ref/index.txt b/docs/ref/index.txt
    a b  
    2121   signals
    2222   templates/index
    2323   unicode
     24   utils
    2425   validators
  • new file docs/ref/utils.txt

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