MCPcopy Create free account
hub / github.com/EasyIME/PIME / linkify

Function linkify

python/python3/tornado/escape.py:275–377  ·  view source on GitHub ↗

Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello http://tornadoweb.org !`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra t

(
    text: Union[str, bytes],
    shorten: bool = False,
    extra_params: Union[str, Callable[[str], str]] = "",
    require_protocol: bool = False,
    permitted_protocols: List[str] = ["http", "https"],
)

Source from the content-addressed store, hash-verified

273
274
275def linkify(
276 text: Union[str, bytes],
277 shorten: bool = False,
278 extra_params: Union[str, Callable[[str], str]] = "",
279 require_protocol: bool = False,
280 permitted_protocols: List[str] = ["http", "https"],
281) -> str:
282 """Converts plain text into HTML with links.
283
284 For example: ``linkify("Hello http://tornadoweb.org!")`` would return
285 ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!``
286
287 Parameters:
288
289 * ``shorten``: Long urls will be shortened for display.
290
291 * ``extra_params``: Extra text to include in the link tag, or a callable
292 taking the link as an argument and returning the extra text
293 e.g. ``linkify(text, extra_params='rel="nofollow" class="external"')``,
294 or::
295
296 def extra_params_cb(url):
297 if url.startswith("http://example.com"):
298 return 'class="internal"'
299 else:
300 return 'class="external" rel="nofollow"'
301 linkify(text, extra_params=extra_params_cb)
302
303 * ``require_protocol``: Only linkify urls which include a protocol. If
304 this is False, urls such as www.facebook.com will also be linkified.
305
306 * ``permitted_protocols``: List (or set) of protocols which should be
307 linkified, e.g. ``linkify(text, permitted_protocols=["http", "ftp",
308 "mailto"])``. It is very unsafe to include protocols such as
309 ``javascript``.
310 """
311 if extra_params and not callable(extra_params):
312 extra_params = " " + extra_params.strip()
313
314 def make_link(m: typing.Match) -> str:
315 url = m.group(1)
316 proto = m.group(2)
317 if require_protocol and not proto:
318 return url # not protocol, no linkify
319
320 if proto and proto not in permitted_protocols:
321 return url # bad protocol, no linkify
322
323 href = m.group(1)
324 if not proto:
325 href = "http://" + href # no proto specified, use http
326
327 if callable(extra_params):
328 params = " " + extra_params(href).strip()
329 else:
330 params = extra_params
331
332 # clip long urls. max_len is just an approximation

Callers

nothing calls this directly

Calls 1

xhtml_escapeFunction · 0.85

Tested by

no test coverage detected