-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtext.py
More file actions
104 lines (79 loc) · 2.29 KB
/
Copy pathtext.py
File metadata and controls
104 lines (79 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import re
from html import unescape
from random import choice
from string import ascii_letters, digits
from markupsafe import Markup, escape, escape_silent
from sidekick import import_later
# qa: used imports
bleach = import_later("bleach")
escape = escape
escape_silent = escape_silent
unescape = unescape
VALID_ID_CHARS = ascii_letters + digits + "_-"
STR_TYPES = (str, bytes, Markup)
SAFE_ATTRIBUTE_NAME = re.compile(r"^[^\s=<>&\"\']+$")
def dash_case(name):
"""
Convert a camel case string to dash case.
Example:
>>> dash_case('SomeName')
'some-name'
"""
letters = []
for c in name:
if c.isupper() and letters and letters[-1] != "-":
letters.append("-" + c.lower())
else:
letters.append(c.lower())
return "".join(letters)
def snake_case(name):
"""
Convert camel case to snake case.
"""
return dash_case(name).replace("-", "_")
def random_id(prefix="id-", size=8):
"""
Return a random valid HTML id.
Args:
prefix:
A prefix string.
size:
The size of the random part of the string. The default value of 8
gives a collision probability of ~ 3.5e-15, which is good enough for
most cases.
Returns:
A random string.
"""
if not prefix:
prefix = choice(ascii_letters)
size -= 1
return prefix + "".join(choice(VALID_ID_CHARS) for _ in range(size))
def safe(x):
"""
Convert string object to a safe Markup instance.
"""
return Markup(x)
def sanitize(data, **kwargs):
"""
Sanitize HTML and return as a safe string.
"""
return safe(bleach.clean(data, **kwargs))
def html_natural_attr(x):
"""
Convert string to a natural HTML attribute or tag name.
This function replaces underscores by dashes.
"""
return x.rstrip("_").replace("_", "-")
def html_safe_natural_attr(x):
"""
Convert string to html natural name and check if the resulting string is
valid.
"""
return check_html_safe_name(html_natural_attr(x))
def check_html_safe_name(x):
"""
Raises a ValueError if string is not a valid html attribute or tag name.
"""
if not SAFE_ATTRIBUTE_NAME.match(x):
raise ValueError("invalid html attribute name: %r" % x)
return x