Passed
Push — main ( bf48fe...dbb226 )
by Sat CFDI
04:49
created

satcfdi.render.json_write()   A

Complexity

Conditions 5

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 19.4658

Importance

Changes 0
Metric Value
cc 5
eloc 6
nop 3
dl 0
loc 7
ccs 1
cts 6
cp 0.1666
crap 19.4658
rs 9.3333
c 0
b 0
f 0
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
PDF_INIT_TEMPLATE = DefaultCFDIEnvironment.get_template("_init.html")
16
17
18 1
def json_write(xlm: XElement, target, pretty_print=False):
19
    if isinstance(target, str):
20
        with open(target, 'w') as f:
21
            json.dump(xlm, f, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
22
            return
23
24
    json.dump(xlm, target, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
25
26
27 1
def json_str(xlm: XElement, pretty_print=False) -> str:
28 1
    return json.dumps(xlm, ensure_ascii=False, default=str, indent=2 if pretty_print else None)
29
30
31 1
def html_write(xlm: XElement | Sequence[XElement], target, init_template=PDF_INIT_TEMPLATE):
32 1
    if isinstance(xlm, Sequence):
33 1
        init_template.stream({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'}).dump(target)
34
    else:
35
        init_template.stream({"c": xlm, "k": QName(xlm.tag).localname}).dump(target)
36
37
38 1
def html_str(xlm: XElement | Sequence[XElement], init_template=PDF_INIT_TEMPLATE) -> str:
39 1
    if isinstance(xlm, Sequence):
40 1
        return init_template.render({"c": [(QName(a.tag).localname, a) for a in xlm], "k": '_multiple'})
41
    else:
42 1
        return init_template.render({"c": xlm, "k": QName(xlm.tag).localname})
43
44
45 1
def pdf_write(xlm: XElement | Sequence[XElement], target, init_template=PDF_INIT_TEMPLATE):
46 1
    if weasyprint is None:
47
        raise ImportError("weasyprint is not installed")
48
49 1
    weasyprint.HTML(string=html_str(xlm, init_template=init_template)).write_pdf(
50
        target=target,
51
        stylesheets=[PDF_CSS]
52
    )
53
54 1
def pdf_bytes(xlm: XElement | Sequence[XElement], init_template=PDF_INIT_TEMPLATE) -> bytes:
55
    if weasyprint is None:
56
        raise ImportError("weasyprint is not installed")
57
58
    return weasyprint.HTML(string=html_str(xlm, init_template=init_template)).write_pdf(
59
        stylesheets=[PDF_CSS]
60
    )
61