Coverage for jutil/responses.py: 42%

# Coverage for jutil/responses.py : 42%

## 39 statements

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

1 import mimetypes

2 import os

3 from typing import Any, List

4 from django.http import HttpResponse, FileResponse, Http404

5 from django.utils.translation import gettext as _

6 from jutil.format import format_xml_file, format_xml_bytes, format_csv

7

8

9 class 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 """

15

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)

27

28

29 class CsvResponse(HttpResponse):

30 """

31 CSV download HTTP response.

32 """

33

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)

45

46

47 class 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))

54

55

56 class 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))

62

63

64 class 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)