MCPcopy Index your code
hub / github.com/python/cpython / _encode_text

Function _encode_text

Lib/email/contentmanager.py:132–169  ·  view source on GitHub ↗
(string, charset, cte, policy)

Source from the content-addressed store, hash-verified

130
131
132def _encode_text(string, charset, cte, policy):
133 # If max_line_length is 0 or None, there is no limit.
134 maxlen = policy.max_line_length or sys.maxsize
135 lines = string.encode(charset).splitlines()
136 linesep = policy.linesep.encode('ascii')
137 def embedded_body(lines): return linesep.join(lines) + linesep
138 def normal_body(lines): return b'\n'.join(lines) + b'\n'
139 if cte is None:
140 # Use heuristics to decide on the "best" encoding.
141 if max(map(len, lines), default=0) <= maxlen:
142 try:
143 return '7bit', normal_body(lines).decode('ascii')
144 except UnicodeDecodeError:
145 pass
146 if policy.cte_type == '8bit':
147 return '8bit', normal_body(lines).decode('ascii', 'surrogateescape')
148 sniff = embedded_body(lines[:10])
149 sniff_qp = quoprimime.body_encode(sniff.decode('latin-1'), maxlen)
150 sniff_base64 = binascii.b2a_base64(sniff)
151 # This is a little unfair to qp; it includes lineseps, base64 doesn't.
152 if len(sniff_qp) > len(sniff_base64):
153 cte = 'base64'
154 else:
155 cte = 'quoted-printable'
156 if len(lines) <= 10:
157 return cte, sniff_qp
158 if cte == '7bit':
159 data = normal_body(lines).decode('ascii')
160 elif cte == '8bit':
161 data = normal_body(lines).decode('ascii', 'surrogateescape')
162 elif cte == 'quoted-printable':
163 data = quoprimime.body_encode(normal_body(lines).decode('latin-1'),
164 maxlen)
165 elif cte == 'base64':
166 data = binascii.b2a_base64(embedded_body(lines), wrapcol=maxlen).decode('ascii')
167 else:
168 raise ValueError("Unknown content transfer encoding {}".format(cte))
169 return cte, data
170
171
172def set_text_content(msg, string, subtype="plain", charset='utf-8', cte=None,

Callers 1

set_text_contentFunction · 0.85

Calls 7

normal_bodyFunction · 0.85
embedded_bodyFunction · 0.85
body_encodeMethod · 0.80
splitlinesMethod · 0.45
encodeMethod · 0.45
decodeMethod · 0.45
formatMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…