本文档涵盖了django.utils
中的所有稳定模块。 django.utils
中的大多数模块都是为内部使用而设计的,只有以下部分才能被视为稳定,因此按照internal release deprecation policy可向后兼容。
django.utils.cache
¶此模块包含用于控制缓存的辅助函数。 它通过管理响应的Vary
标头来实现。 它包括直接修补响应对象的头部的函数和修改函数的修饰器来做自己的头部修补。
有关Vary
头的信息,请参见 RFC 7231#section-7.1.4。
本质上,Vary
HTTP头定义了缓存在构建缓存键时应考虑哪些头。 对于在Vary
中命名的头,具有相同路径但头部内容不同的请求需要获得不同的缓存键,以防止传送错误的内容。
例如,internationalization中间件需要通过Accept-language
头区分缓存。
patch_cache_control
(response, **kwargs)[source]¶此函数通过向Cache-Control
头中添加所有关键字参数来修补它。 变换如下:
True
(确切地为True
,而不仅仅是一个真值),则只有参数名称会添加到标题中。str()
应用到它之后,所有其他参数都与它们的值相加。patch_response_headers
(response, cache_timeout=None)[source]¶向给定的HttpResponse
对象添加一些有用的标题:
ETag的
过期
缓存控制
每个标头仅在尚未设置时才添加。
cache_timeout
以秒为单位。 默认情况下使用CACHE_MIDDLEWARE_SECONDS
设置。
在旧版本中,也设置了Last-Modified
头。
自1.11版以来已弃用 由于USE_ETAGS
设置已被弃用,当Django 2.1中的弃用结束时,此功能将不会设置ETag
头。
patch_vary_headers
(response, newheaders)[source]¶在给定的Vary
对象中添加(或更新)HttpResponse
标题。
newheaders
是应该在Vary
中的标题名称列表。
Vary
中的现有标题不会被删除。
django.utils.dateparse
¶此模块中定义的函数共享以下属性:
ValueError
。None
。parse_date
(value)[source]¶解析字符串并返回datetime.date
。
parse_time
(value)[source]¶解析字符串并返回datetime.time
。
不支持UTC偏移;如果value
描述一个,结果为None
。
parse_datetime
(value)[source]¶解析字符串并返回datetime.datetime
。
支持UTC偏移;如果value
描述一个,则结果的tzinfo
属性是FixedOffset
实例。
parse_duration
(value)[source]¶解析字符串并返回datetime.timedelta
。
Expects data in the format "DD HH:MM:SS.uuuuuu"
or as specified by ISO
8601 (e.g. P4DT1H15M20S
which is equivalent to 4 1:15:20
).
django.utils.decorators
¶method_decorator
(装饰器,name ='')[source] ¶将函数装饰器转换为方法装饰器。 它可以用来装饰方法或类;在后一种情况下,name
是要进行装饰和需要的方法的名称。
decorator
也可以是列表或元组的功能。 它们以相反的顺序包装,以便调用顺序是函数在列表/元组中出现的顺序。
有关示例用法,请参见decorating class based views。
decorator_from_middleware
(middleware_class)[source]¶给定一个中间件类,返回一个视图装饰器。 这使您可以在每个视图的基础上使用中间件功能。 中间件创建时没有传递参数。
它假定与旧版Django 1.9及更早版本兼容的中间件(具有process_request()
,process_exception()
和process_response()
decorator_from_middleware_with_args
(middleware_class)[source]¶像decorator_from_middleware
,但返回一个函数,接受要传递给middleware_class的参数。
例如,cache_page()
装饰器是从CacheMiddleware
创建的,如下所示:
cache_page = decorator_from_middleware_with_args(CacheMiddleware)
@cache_page(3600)
def my_view(request):
pass
django.utils.encoding
¶python_2_unicode_compatible
()[source]¶在Python 2下定义__unicode__
和__str__
方法的装饰器。 在Python 3下它什么也不做。
要使用单个代码库支持Python 2和3,请定义__str__
方法返回文本(如果您正在进行某些转换,请使用six.text_type()
)并应用此装修师上课
smart_text
(s, encoding='utf-8', strings_only=False, errors='strict')[source]¶返回代表Python 3上的s
- unicode
和Python 3上的str
的文本对象。 使用encoding
编码解码器处理。
如果strings_only
是True
,请勿转换(一些)非字符串对象。
smart_unicode
(s, encoding='utf-8', strings_only=False, errors='strict')¶smart_text()
的历史名称。 仅在Python 2下可用。
force_text
(s, encoding='utf-8', strings_only=False, errors='strict')[source]¶类似于smart_text
,除了延迟实例被解析为字符串,而不是保持为延迟对象。
如果strings_only
是True
,请勿转换(一些)非字符串对象。
force_unicode
(s, encoding='utf-8', strings_only=False, errors='strict')¶force_text()
的历史名称。 仅在Python 2下可用。
smart_bytes
(s, encoding='utf-8', strings_only=False, errors='strict')[source]¶返回s
中指定的encoding
的按测试版本。
如果strings_only
是True
,请勿转换(一些)非字符串对象。
force_bytes
(s, encoding='utf-8', strings_only=False, errors='strict')[source]¶类似于smart_bytes
,除了延迟实例被解析为bytestrings,而不是保持为延迟对象。
如果strings_only
是True
,请勿转换(一些)非字符串对象。
smart_str
(s, encoding='utf-8', strings_only=False, errors='strict')¶Python 2上的smart_bytes()
的别名和Python 3上的smart_text()
。 此函数返回str
或惰性字符串。
例如,这适合于在Python 2和3上写入sys.stdout
。
force_str
(s, encoding='utf-8', strings_only=False, errors='strict')¶Python 2上的force_bytes()
的别名和在Python 3上的force_text()
。 此函数始终返回str
。
iri_to_uri
(iri)[source]¶将国际化资源标识符(IRI)部分转换为适合包含在URL中的URI部分。
这是 RFC 3987#section-3.1的3.1节的算法。 然而,由于我们假设输入是UTF-8或unicode已经,我们可以简化东西一点从完整的方法。
采用UTF-8字节的IRI,并返回包含编码结果的ASCII字节。
uri_to_iri
(uri)[source]¶将统一资源标识符转换为国际化资源标识符。
这是来自 RFC 3987#section-3.2的3.2节的算法。
获取ASCII字节的URI,并返回包含编码结果的Unicode字符串。
django.utils.feedgenerator
¶样品用量:
>>> from django.utils import feedgenerator
>>> feed = feedgenerator.Rss201rev2Feed(
... title="Poynter E-Media Tidbits",
... link="http://www.poynter.org/column.asp?id=31",
... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
... language="en",
... )
>>> feed.add_item(
... title="Hello",
... link="http://www.holovaty.com/test/",
... description="Testing.",
... )
>>> with open('test.rss', 'w') as fp:
... feed.write(fp, 'utf-8')
为了简化发电机的选择,使用feedgenerator.DefaultFeed
,目前为Rss201rev2Feed
有关不同版本的RSS的定义,请参阅:https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss t0 >
get_tag_uri
(url, date)[source]¶创建一个TagURI。
见https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
SyndicationFeed
¶SyndicationFeed
[source]¶所有联合供稿的基类。 子类应提供write()。
__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)[source]¶使用给定的元数据字典初始化Feed,该元数据字典应用于整个Feed。
任何传递到__init__
的额外关键字参数将存储在self.feed
中。
所有参数都应该是Unicode对象,除了categories
,它应该是Unicode对象序列。
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, updateddate=None, enclosures=None, **kwargs)[source]¶向Feed中添加项目。 All args are expected to be Python unicode
objects except pubdate
and updateddate
, which are datetime.datetime
objects, enclosure
, which is an Enclosure
instance, and
enclosures
, which is a list of Enclosure
instances.
自1.9版以来已弃用 enclosure
关键字参数已被弃用,有利于接受Enclosure
对象列表的新的enclosures
关键字参数。
django.utils.functional
¶cached_property
(object,name)[source] ¶@cached_property
装饰器将具有单个self
参数的方法的结果作为属性进行缓存。 缓存的结果只要实例持续存在,如果实例被传递并且函数随后被调用,则将返回缓存的结果。
考虑一个典型的情况,其中视图可能需要调用模型的方法来执行一些计算,然后将模型实例放入上下文中,其中模板可能再次调用该方法:
# the model
class Person(models.Model):
def friends(self):
# expensive computation
...
return friends
# in the view:
if person.friends():
...
在模板中,你会有:
{% for friend in person.friends %}
这里,friends()
将被调用两次。 由于视图中的实例person
和模板相同,因此使用@cached_property
装饰friends()
方法可避免:
from django.utils.functional import cached_property
class Person(models.Model):
@cached_property
def friends(self):
...
注意,由于方法现在是一个属性,在Python代码中,它需要被适当地调用:
# in the view:
if person.friends:
...
缓存的值可以像实例的普通属性一样处理:
# clear it, requiring re-computation next time it's called
del person.friends # or delattr(person, "friends")
# set a value manually, that will persist on the instance until cleared
person.friends = ["Huckleberry Finn", "Tom Sawyer"]
除了提供潜在的性能优势,@cached_property
可以确保属性的值在实例的整个生命周期内不会意外更改。 这可能发生在一个方法的计算是基于datetime.now()
,或者简单地如果一个更改被保存到数据库的一些其他进程在一个方法的后续调用之间的短暂的时间间隔同一个实例。
您可以使用name
参数来创建其他方法的缓存属性。 例如,如果你有一个昂贵的get_friends()
方法,并希望允许调用它而不检索缓存的值,你可以写:
friends = cached_property(get_friends, name='friends')
虽然person.get_friends()
会在每次调用时重新计算朋友,但缓存属性的值将持续,直到您如上所述将其删除:
x = person.friends # calls first time
y = person.get_friends() # calls again
z = person.friends # does not call
x is z # is True
allow_lazy
(func, *resultclasses)[source]¶自1.10版以来已弃用。
像keep_lazy()
一样工作,除了它不能用作装饰器。
keep_lazy
(func, *resultclasses)[source]¶Django提供了许多效用函数(特别是在django.utils
),它们接受一个字符串作为它们的第一个参数,并对该字符串进行操作。
这些函数由模板过滤器使用,也可以直接在其他代码中使用。
如果你写自己的类似的功能和处理翻译,你会面临的问题,当第一个参数是一个延迟翻译对象做什么。 您不想立即将其转换为字符串,因为您可能在视图之外使用此函数(因此当前线程的语言环境设置将不正确)。
对于这种情况,请使用django.utils.functional.keep_lazy()
装饰器。 它修改函数,使得if使用延迟转换作为其参数之一调用,函数求值将被延迟,直到需要将其转换为字符串。
像这样:
from django.utils import six
from django.utils.functional import keep_lazy, keep_lazy_text
def fancy_utility_function(s, ...):
# Do some conversion on string 's'
...
fancy_utility_function = keep_lazy(six.text_type)(fancy_utility_function)
# Or more succinctly:
@keep_lazy(six.text_type)
def fancy_utility_function(s, ...):
...
keep_lazy()
装饰器需要一些额外的参数(*args
),指定原始函数可以返回的类型。 一个常见的用例是具有返回文本的函数。 对于这些,您可以将six.text_type
类型传递给keep_lazy
(或者更简单,使用下一个描述的keep_lazy_text()
装饰器部分)。
使用这个装饰器意味着你可以编写你的函数,并假设输入是一个合适的字符串,然后在末尾添加对延迟翻译对象的支持。
keep_lazy_text
(func)[source]¶keep_lazy(six.text_type)(func)
的快捷方式。
如果你有一个返回文本的函数,并且希望在延迟评估时能够采取懒惰的参数,那么只需使用这个装饰器:
from django.utils import six
from django.utils.functional import keep_lazy, keep_lazy_text
# Our previous example was:
@keep_lazy(six.text_type)
def fancy_utility_function(s, ...):
...
# Which can be rewritten as:
@keep_lazy_text
def fancy_utility_function(s, ...):
...
django.utils.html
¶通常,您应该使用Django的模板来构建HTML,以使用其自动缩放机制,并在适当的位置使用django.utils.safestring
中的实用程序。 此模块提供一些额外的低级实用程序用于转义HTML。
escape
(text)[source]¶返回给定文本,并带有用于HTML的带符号,引号和尖括号。 输入首先通过force_text()
,输出具有mark_safe()
。
format_html
(format_string, *args, **kwargs)[source]¶这类似于str.format()
,除了它适合于构建HTML片段。 所有args和kwarg在传递到str.format()
之前通过conditional_escape()
传递。
对于构建小HTML片段的情况,直接使用%
或str.format()
的字符串插值优先,因为它适用于转义为所有参数 - 就像模板系统默认应用转义。
所以,而不是写:
mark_safe("%s <b>%s</b> %s" % (
some_html,
escape(some_text),
escape(some_other_text),
))
您应该使用:
format_html("{} <b>{}</b> {}",
mark_safe(some_html),
some_text,
some_other_text,
)
这具有的优点是,您不需要对每个参数应用escape()
,并且如果您忘记了一个漏洞和一个XSS漏洞,就有风险。
请注意,虽然此函数使用str.format()
进行插值,但是由str.format()
提供的某些格式化选项(例如数字格式化)将无法正常工作因为所有参数都通过conditional_escape()
(最终)调用force_text()
。
format_html_join
(sep, format_string, args_generator)[source]¶format_html()
的包装器,用于需要使用相同格式字符串格式化的一组参数的常见情况,然后使用sep
连接。 sep
也通过conditional_escape()
传递。
args_generator
应为一个迭代器,它返回将传递给format_html()
的args
序列。 像这样:
format_html_join(
'\n', "<li>{} {}</li>",
((u.first_name, u.last_name) for u in users)
)
尝试从字符串中删除任何看起来像HTML标记的内容,即<>
中包含的任何内容。
绝对不保证结果字符串是HTML安全。 因此,请不要将strip_tag
调用的结果标记为安全,而不首先转义它,例如使用escape()
。
像这样:
strip_tags(value)
如果value
是“&lt; b&gt; Joel&lt; / b&gt; &lt; button&gt;是&lt; / button&gt; a &lt; span&gt; slug&lt; / span&gt;“
返回值将为”Joel a slug“
。
如果您正在寻找更强大的解决方案,请查看bleach Python库。
html_safe
()[source]¶类上的__html__()
方法可帮助非Django模板检测其输出不需要HTML转义的类。
这个装饰器通过将__unicode__()
(Python 2)或__str__()
(Python 3)来定义装饰类上的__html__()
)在mark_safe()
中。 确保__unicode__()
或__str__()
方法确实返回不需要HTML转义的文本。
django.utils.http
¶urlquote
(url, safe='/')[source]¶Python的urllib.quote()
函数,可以对unicode字符串进行操作。 url在引用前首先进行UTF-8编码。 返回的字符串可以安全地用作后续iri_to_uri()
调用的参数的一部分,而不会发生双引号。 实现延迟执行。
urlquote_plus
(url, safe='')[source]¶Python的urllib.quote_plus()函数的版本,可以对unicode字符串进行操作。 url在引用前首先进行UTF-8编码。 返回的字符串可以安全地用作后续iri_to_uri()
调用的参数的一部分,而不会发生双引号。 实现延迟执行。
urlencode
(query, doseq=0)[source]¶Python的urllib.urlencode()函数的版本,可以对unicode字符串进行操作。 参数首先转换为UTF-8编码字符串,然后按照正常编码。
格式化时间以确保与Netscape的Cookie标准兼容。
接受以UTC表示的纪元以秒表示的浮点数,例如由time.time()
输出的浮点数。 如果设置为None
,则默认为当前时间。
输出格式为Wdy, DD-Mon-YYYY HH:MM:SS GMT
。
http_date
(epoch_seconds=None)[source]¶格式化时间匹配HTTP RFC 7231#section-7.1.1.1指定的 RFC 1123日期格式。
接受以UTC表示的纪元以秒表示的浮点数,例如由time.time()
输出的浮点数。 如果设置为None
,则默认为当前时间。
输出格式为Wdy, DD Mon YYYY GMT
。
int_to_base36
(i)[source]¶将正整数转换为基本36个字符串。 在Python 2 i
必须小于sys.maxint。
django.utils.safestring
¶使用“安全字符串”的函数和类:可以安全显示而无需在HTML中进一步转义的字符串。 将某些东西标记为“安全的字符串”意味着字符串的制作者已经将不被HTML引擎解释的字符(例如“
mark_safe
(s)[source]¶将字符串明确标记为(HTML)输出目的的安全。 返回的对象可以在任何地方使用字符串或unicode对象是适当的。
可以在单个字符串上调用多次。
也可以用作装饰器。
对于构建HTML的片段,通常应使用django.utils.html.format_html()
。
标记为安全的字符串将变得不安全,如果修改。 像这样:
>>> mystr = '<b>Hello World</b> '
>>> mystr = mark_safe(mystr)
>>> type(mystr)
<class 'django.utils.safestring.SafeBytes'>
>>> mystr = mystr.strip() # removing whitespace
>>> type(mystr)
<type 'str'>
增加了对装饰器使用的支持。
django.utils.text
¶format_lazy
(format_string, *args, **kwargs)¶当format_string
,args
和/或kwargs
时,str.format()
的版本包含懒惰对象。 第一个参数是要格式化的字符串。 像这样:
from django.utils.text import format_lazy
from django.utils.translation import pgettext_lazy
urlpatterns = [
url(format_lazy(r'{person}/(?P<pk>\d+)/$', person=pgettext_lazy('URL', 'person')),
PersonDetailView.as_view()),
]
此示例允许翻译者翻译URL的一部分。 如果“person”被翻译为“persona”,则正则表达式将匹配persona/(?P<pk>\d+)/$
,例如persona/5/
slugify
(allow_unicode=False)[source]¶如果allow_unicode
为False
(默认),则转换为ASCII。 将空格转换为连字符。 删除不是字母数字,下划线或连字符的字符。 转换为小写。 还剥离前导和尾随空格。
像这样:
slugify(value)
如果value
是“Joel 是 a slug” t2 >,输出将为
"joel-is-a-slug"
。
如果要允许Unicode字符,可以将allow_unicode
参数设置为True
slugify(value, allow_unicode=True)
如果value
是“你好 世界”
,输出将为"你好-world"
django.utils.timezone
¶get_fixed_timezone
(offset)[source]¶返回一个tzinfo
实例,该实例表示与UTC具有固定偏移量的时区。
offset
是一个datetime.timedelta
实例或一个表示分钟的整数。 UTC以东的时区使用正值,UTC以西的时区使用负值。
get_default_timezone
()[source]¶返回表示default time zone的tzinfo
实例。
get_default_timezone_name
()[source]¶返回default time zone的名称。
get_current_timezone
()[source]¶返回表示current time zone的tzinfo
实例。
get_current_timezone_name
()[source]¶返回current time zone的名称。
activate
(timezone)[source]¶设置current time zone。 timezone
参数必须是tzinfo
子类或时区名称的实例。
deactivate
()[source]¶取消设置current time zone。
override
(timezone)[source]¶这是一个Python上下文管理器,用于在activate()
的条目上设置current time zone,并在退出时恢复以前活动的时区。 如果timezone
参数为None
,则current time zone在输入时取消设置,而改为使用deactivate()
。
override
也可用作函数装饰器。
localtime
(value=None, timezone=None)[source]¶将感知到的datetime
转换为不同的时区,默认为current time zone。
当value
被省略时,它默认为now()
。
此功能在天真的数据时间不工作;请改用make_aware()
。
在旧版本中,value
是必需的参数。
localdate
(value=None, timezone=None)[source]¶使用localtime()
将一个有意义的datetime
转换为不同时区的date()
,默认情况下current time zone
当value
被省略时,它默认为now()
。
此功能在初始数据时间上不起作用。
make_aware
(value, timezone=None, is_dst=None)[source]¶返回代表timezone
中的value
的相同时间点的datetime
,value
是一个天真的datetime
如果timezone
设置为None
,则默认为current time zone。
如果在DST转换期间尝试使value
感知到同时发生两次(当从DST还原时),则引发pytz.AmbiguousTimeError
异常。 将is_dst
设置为True
或False
将通过选择是否分别进行转换前或转换后来避免异常。
如果您在DST转换期间尝试使value
值得注意,从而不会发生时间(输入DST时),则会引发pytz.NonExistentTimeError
异常。 将is_dst
设置为True
或False
将通过分别将小时向后或向后移动1来避免异常。 例如,is_dst=True
会将不存在的时间改为2:30至1:30,而is_dst=False
会将时间更改为3:30。
make_naive
(value, timezone=None)[source]¶Returns an naive datetime
that represents in timezone
the same point in time as value
, value
being an aware datetime
. 如果timezone
设置为None
,则默认为current time zone。
django.utils.translation
¶有关以下用法的完整讨论,请参阅translation documentation。
pgettext
(context, message)[source]¶转换message
给定context
并返回一个unicode字符串。
有关详细信息,请参阅Contextual markers。
gettext_lazy
(message)¶ugettext_lazy
(message)¶pgettext_lazy
(context, message)¶与上面的非惰性版本相同,但使用惰性执行。
ugettext_noop
(message)¶标记要翻译的字符串,但不会立即翻译。 这可以用于将字符串存储在应该保持基本语言的全局变量中(因为它们可能在外部使用),并且稍后将被翻译。
npgettext
(context, singular, plural, number)[source]¶翻译singular
和plural
,并在unicode字符串中返回基于context
和number
的适当字符串。
string_concat
(*strings)¶自1.11版以来已弃用 改用django.utils.text.format_lazy()
。
string_concat(*strings)
可以替换为format_lazy('{}' * len(strings) t5> * strings)
。
字符串连接的延迟变体,需要从多个部分构建的翻译。
override
(language, deactivate=False)[source]¶使用django.utils.translation.activate()
来获取给定语言的翻译对象的Python上下文管理器将其作为当前线程的翻译对象激活,并在退出时重新激活上一个活动语言。
或者,如果deactivate
参数为True
,则可以使用django.utils.translation.deactivate()
退出退出临时转换。 如果传递None
作为语言参数,则在上下文中激活NullTranslations()
实例。
override
也可用作函数装饰器。
get_language
()[source]¶返回当前选择的语言代码。 如果暂时停用翻译(通过deactivate_all()
或将None
传递给override()
),则返回None
。
get_language_from_request
(request, check_path=False)[source]¶分析请求以找到用户希望系统显示哪种语言。 仅考虑在settings.LANGUAGES中列出的语言。 如果用户请求一个具有主语言的子语言,我们发出主语言。
如果check_path
为True
,则函数首先检查所请求的URL,以确定其路径是否以LANGUAGES
设置中列出的语言代码开头。
LANGUAGE_SESSION_KEY
¶存储当前会话的活动语言的会话密钥。
2017年9月6日