探索Django utils

探索Django utils

Posted November 16, 2018

Django utils 提供了很多實用的功能.

Crypto

Module: django.utils.crypto

get_random_string

獲取隨機字符串函數, 默認是返回長度爲12的隨機字符串。 可以通過參數傳遞長度.

Python

from django.utils.crypto import get_random_string

get_random_string()

Python

output

'5QxAxqyhsyJM'

你可以傳遞參數, 獲取指定長度的字符串

Python

get_random_string(50)

Python

output

'lrWYnyxhnXpwmjHDzmdgTFaIi1j73cKD5fPDOPwuVBmmKxITYF'

也可以指定字符串的選值範圍

Python

get_random_string(12, '0123456789')

Python

output

'805379737758'

Dates

Module: django.utils.dates

常用日期的集合, 日期的人性化顯示.

WEEKDAYS

Python

from django.utils.dates import WEEKDAYS

Python

WEEKDAYS = {
    0: _('Monday'), 1: _('Tuesday'), 2: _('Wednesday'), 3: _('Thursday'), 4: _('Friday'),
    5: _('Saturday'), 6: _('Sunday')
}

WEEKDAYS_ABBR

Python

from django.utils.dates import WEEKDAYS_ABBR

Python

WEEKDAYS_ABBR = {
    0: _('Mon'), 1: _('Tue'), 2: _('Wed'), 3: _('Thu'), 4: _('Fri'),
    5: _('Sat'), 6: _('Sun')
}

MONTHS

Python

from django.utils.dates import MONTHS

Python

MONTHS = {
    1: _('January'), 2: _('February'), 3: _('March'), 4: _('April'), 5: _('May'), 6: _('June'),
    7: _('July'), 8: _('August'), 9: _('September'), 10: _('October'), 11: _('November'),
    12: _('December')
}

DateFormat

Module: django.utils.dateformat

一個很棒的日期格式化模塊

format

Python

from django.utils.dateformat import format
from django.utils import timezone

now = timezone.now()    # datetime.datetime(2018, 11, 16, 6, 48, 41, 351928, tzinfo=<UTC>)
format(now, 'd M Y')

Python

output

u'16 Nov 2018'

日期和時間一起

Python

format(now, 'd/m/Y H:i')

Python

output

u'16/11/2018 06:48'

DateParse

Module: django.utils.dateparse

將格式化後的字符串轉爲 date/time/datetime 對象. 如果字符串格式正確, 但表示無效時間將會返回 None.

parse_date

Python

from django.utils.dateparse import parse_date

parse_date('2018-11-16')

Python

output

datetime.date(2018, 11, 16)

parse_time

Python

from django.utils.dateparse import parse_time

parse_time('14:54:02')

Python

output

datetime.time(14, 54, 2)

parse_datetime

Python

from django.utils.dateparse import parse_datetime

parse_datetime('2018-11-16 14:54:02')

Python

output

datetime.datetime(2018, 11, 16, 14, 54, 2)

HTML

Module: django.utils.html

urlize

將文本中的網址轉換爲<a>標籤

Python

from django.utils.html import urlize

urlize('You guys should visit this website www.google.com')
print urlize('Please visit:  https://jackeygao.io')

Python

output

'You guys should visit this website <a href="http://www.google.com">www.google.com</a>'
Please visit:  <a href="https://jackeygao.io">https://jackeygao.io</a>

他也適用於email地址

Python

urlize('Send me a message to [email protected]')

Python

output

'Send me a message to <a href="mailto:[email protected]">[email protected]</a>'

你也可以修剪鏈接顯示部分長度, 不足處以'...'替代

Python

urlize('Please visit https://jackeygao.io/words/django-exploring-utils.html', 24)

Python

output

Please visit <a href="https://jackeygao.io/words/django-exploring-utils.html">https://jackeygao.io/...</a>

escape

對html 特殊字符編碼

Python

from django.utils.html import escape

escape("<strong style='font-size: 12px'>escaped html</strong>")

Python

output

'&lt;strong style=&#39;font-size: 12px&#39;&gt;escaped html&lt;/strong&gt;'

這將導致已轉義的字符串再次被轉義

Python

escaped_html = escape("<strong>escaped html</strong>")
# '&lt;strong&gt;escaped html&lt;/strong&gt;'

escape(escaped_html)
# '&amp;lt;strong&amp;gt;escaped html&amp;lt;/strong&amp;gt;'

如果不想這樣, 請改用conditional_escape()

conditional_escape

Python

escaped_html = conditional_escape("<strong>escaped html</strong>")
# '&lt;strong&gt;escaped html&lt;/strong&gt;'

conditional_escape(escaped_html)
# '&lt;strong&gt;escaped html&lt;/strong&gt;'

format_html

此函數類似格式化字符串(str.format()), 因爲安全的原因推薦使用format_html.

Python

from django.utils.html import format_html

format_html('<div class="alert {}">{}</>', 'warning', 'Watch out!')

Python

output

'<div class="alert warning">Watch out!</>'

安全的格式化 HTML 代碼.

Python

format_html('<div class="alert {}">{}</>', '<script>alert(1);</script>', 'Watch out!')

Python

output

'<div class="alert &lt;script&gt;alert(1);&lt;/script&gt;">Watch out!</>'

format_html_join

適用於快速用相同的方式格式化一組列表

Python

format_html_join('\n', '<p>{}</p>', ['a', 'b', 'c'])

Python

output

<p>a</p>\n<p>b</p>\n<p>c</p>

另外一個例子

Python

data = [
    ['success', 'Success message'],
    ['warning', 'Watch out!'],
    ['danger', 'Danger!!'],
]

format_html_join('\n', '<div class="alert {0}">{1}</div>', data)

Python

output

<div class="alert success">Success message</div>\n
<div class="alert warning">Watch out!</div>\n
<div class="alert danger">Danger!!</div>

和表格一起使用, 當然也可以和ul li一起使用.

Python

format_html_join('\n', '<tr><td>{0}</td><td>{1}</td></tr>', ((u.first_name, u.last_name)
                                                            for u in users))

Python

output

<tr><td>Vitor</td><td>Freitas</td></tr>\n
<tr><td>John</td><td>Duo</td></tr>\n
<tr><td>Peter</td><td>Croke</td></tr>\n
<tr><td>Elektra</td><td>Moore</td></tr>

linebreaks

快速將\n轉換爲<br />

Python

from django.utils.html import linebreaks

linebreaks('convert\ninto html paragraphs\ntest')

Python

output

<p>convert<br />into html paragraphs<br />test</p>

就是這樣, 我希望你也能找到一些有趣的函數, 歡迎通過留言推薦.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章