-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformatting.py
More file actions
51 lines (34 loc) · 1.83 KB
/
Copy pathformatting.py
File metadata and controls
51 lines (34 loc) · 1.83 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
"""How a raw record is turned into the string callers see.
Presentation was previously inlined in the lookup path, which is why the record
had to be HTML-escaped there and un-escaped again in the handler. Keeping it a
strategy means a caller that wants plain text can ask for it instead of undoing
markup that should never have been added.
"""
from abc import ABC, abstractmethod
from .text import html_entities, html_entity_decode, nl2br, strip_tags
from .transport import RawResponse
__all__ = ["RecordFormatter", "HtmlRecordFormatter", "PlainRecordFormatter"]
class RecordFormatter(ABC):
"""Renders a fetched record for display."""
@abstractmethod
def format(self, response: RawResponse) -> str:
"""Return the record as it should be presented."""
def to_plain_text(self, formatted: str) -> str:
"""Undo :meth:`format` as far as possible, for callers wanting raw text."""
return formatted
def __repr__(self) -> str:
return "{}()".format(type(self).__name__)
class HtmlRecordFormatter(RecordFormatter):
"""Escapes the record and marks up its line breaks, as the PHP client does.
Tags are stripped first when the transport reports the body is markup, so an
HTML error page does not arrive with its own tags escaped into the record.
"""
def format(self, response: RawResponse) -> str:
text = strip_tags(response.text) if response.contains_markup else response.text
return nl2br(html_entities(text))
def to_plain_text(self, formatted: str) -> str:
return html_entity_decode(strip_tags(formatted))
class PlainRecordFormatter(RecordFormatter):
"""Returns the record as text, stripping tags when the body is markup."""
def format(self, response: RawResponse) -> str:
return strip_tags(response.text) if response.contains_markup else response.text