Coverage for jutil/responses.py : 42%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import mimetypes
2import os
3from typing import Any, List
4from django.http import HttpResponse, FileResponse, Http404
5from django.utils.translation import gettext as _
6from jutil.format import format_xml_file, format_xml_bytes, format_csv
9class FileSystemFileResponse(FileResponse):
10 """
11 File system download HTTP response.
12 :param full_path: Full path to file
13 :param filename: Filename (optional) passed to client. Defaults to basename of the full path.
14 """
16 def __init__(self, full_path: str, filename: str = "", **kw):
17 if not os.path.isfile(full_path):
18 raise Http404(_("File {} not found").format(full_path))
19 if not filename:
20 filename = os.path.basename(full_path)
21 content_type = mimetypes.guess_type(filename)[0]
22 super().__init__(open(full_path, "rb"), **kw)
23 if content_type:
24 self["Content-Type"] = content_type
25 self["Content-Length"] = os.path.getsize(full_path)
26 self["Content-Disposition"] = "attachment; filename={}".format(filename)
29class CsvResponse(HttpResponse):
30 """
31 CSV download HTTP response.
32 """
34 def __init__(self, rows: List[List[Any]], filename: str, dialect="excel", **kw):
35 """
36 Returns CSV response.
37 :param rows: List of column lists
38 :param filename: Download response file name
39 :param dialect: See csv.writer dialect
40 :param kw: Parameters to be passed to HttpResponse __init__
41 """
42 buf = format_csv(rows, dialect=dialect).encode("utf-8")
43 super().__init__(content=buf, content_type="text/csv", **kw)
44 self["Content-Disposition"] = 'attachment;filename="{}"'.format(filename)
47class FormattedXmlFileResponse(HttpResponse):
48 def __init__(self, filename: str):
49 content = format_xml_file(filename)
50 super().__init__(content)
51 self["Content-Type"] = "application/xml"
52 self["Content-Length"] = len(content)
53 self["Content-Disposition"] = "attachment; filename={}".format(os.path.basename(filename))
56class XmlResponse(HttpResponse):
57 def __init__(self, content: bytes, filename: str):
58 super().__init__(content)
59 self["Content-Type"] = "application/xml"
60 self["Content-Length"] = len(content)
61 self["Content-Disposition"] = "attachment; filename={}".format(os.path.basename(filename))
64class FormattedXmlResponse(XmlResponse):
65 def __init__(self, content: bytes, filename: str, encoding: str = "UTF-8", exceptions: bool = True):
66 super().__init__(format_xml_bytes(content, encoding=encoding, exceptions=exceptions), filename)