Ticket #3469: django_utils_ref.diff

File django_utils_ref.diff, 17.4 KB (added by Joshua Russo, 15 years ago)

Documented django.utils modules listed within API stability section

  • docs/misc/api-stability.txt

     
    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

     
    2121   signals
    2222   templates/index
    2323   unicode
     24   utils
    2425   validators
  • docs/ref/utils.txt

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