satcfdi.render   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 66.67%

Importance

Changes 0
Metric Value
wmc 15
eloc 40
dl 0
loc 62
ccs 24
cts 36
cp 0.6667
rs 10
c 0
b 0
f 0

6 Functions

Rating   Name   Duplication   Size   Complexity  
A html_str() 0 5 2
A pdf_write() 0 7 2
A json_write() 0 7 5
A pdf_bytes() 0 6 2
A json_str() 0 2 2
A html_write() 0 5 2
1 1
import json
2 1
from collections.abc import Sequence
3 1
from lxml.etree import QName
4
5 1
from .environment import DefaultCFDIEnvironment
6 1
from ..xelement import XElement
7
8 1
try:
9 1
    import weasyprint
10
11 1
    PDF_CSS = weasyprint.CSS(string="@page {margin: 1.0cm 1.27cm 1.1cm 0.85cm;}")
12
except OSError as ex:
13
    weasyprint = None
14
15 1
MAIN_TEMPLATE = DefaultCFDIEnvironment.get_template("_main.html")
16 1
BODY_TEMPLATE = DefaultCFDIEnvironment.get_template("_body.html")
17
18
19 1
def json_write(xlm: XElement, target, pretty_print=False):
20
    if isinstance(target, str):
21
        with open(target, 'w') as f:
22
            json.dump(xlm, f, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
23
            return
24
25
    json.dump(xlm, target, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
26
27
28 1
def json_str(xlm: XElement, pretty_print=False) -> str:
29 1
    return json.dumps(xlm, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
30
31
32 1
def html_write(xlm: XElement | Sequence[XElement], target, template=MAIN_TEMPLATE):
33 1
    if isinstance(xlm, Sequence):
34 1
        template.stream({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'}).dump(target)
35
    else:
36
        template.stream({"c": xlm, "k": QName(xlm.tag).localname}).dump(target)
37
38
39 1
def html_str(xlm: XElement | Sequence[XElement], template=MAIN_TEMPLATE) -> str:
40 1
    if isinstance(xlm, Sequence):
41 1
        return template.render({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'})
42
    else:
43 1
        return template.render({"c": xlm, "k": QName(xlm.tag).localname})
44
45
46 1
def pdf_write(xlm: XElement | Sequence[XElement], target, template=MAIN_TEMPLATE):
47 1
    if weasyprint is None:
48
        raise ImportError("weasyprint is not installed")
49
50 1
    weasyprint.HTML(string=html_str(xlm, template=template)).write_pdf(
51
        target=target,
52
        stylesheets=[PDF_CSS]
53
    )
54
55
56 1
def pdf_bytes(xlm: XElement | Sequence[XElement], template=MAIN_TEMPLATE) -> bytes:
57
    if weasyprint is None:
58
        raise ImportError("weasyprint is not installed")
59
60
    return weasyprint.HTML(string=html_str(xlm, template=template)).write_pdf(
61
        stylesheets=[PDF_CSS]
62
    )
63