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