-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathexport.py
139 lines (118 loc) · 6 KB
/
export.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# coding=utf-8
__author__ = "Jarek Szczepanski <[email protected]>"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 Jarek Szczepanski - Released under terms of the AGPLv3 License"
def exportHistoryData(self, exportType):
import flask
import sys
if sys.version_info >= (3,0):
from io import StringIO
from io import BytesIO
import csv
else:
from StringIO import StringIO
import unicodecsv as csv
import re
from .utils import namedtuple_with_defaults, prepare_dict, load_json, rename_duplicates
history_dict = self._getHistoryDict()
if history_dict is not None:
si = StringIO()
headers = ['File name', 'Timestamp', 'Success', 'Print time', 'Spool', 'Filament length', 'Filament volume', 'User']
fields = ['fileName', 'timestamp', 'success', 'printTime', 'spool', 'filamentLength', 'filamentVolume', 'user']
if exportType == 'csv':
if sys.version_info >= (3,0):
writer = csv.writer(si, quoting=csv.QUOTE_ALL)
else:
writer = csv.writer(si, quoting=csv.QUOTE_ALL, encoding='utf-8')
writer.writerow(headers)
for historyDetails in history_dict:
output = list()
for field in fields:
value = historyDetails.get(field, '-')
if field == "timestamp":
output.append(formatTimestamp(value))
elif field == "printTime":
output.append(formatPrintTime(value))
else:
output.append(value if value is not None else '-')
writer.writerow(output);
response = flask.make_response(si.getvalue())
response.headers["Content-type"] = "text/csv"
response.headers["Content-Disposition"] = "attachment; filename=octoprint_print_history_export.csv"
elif exportType == 'csv_extra':
fields = ['fileName', 'timestamp', 'success', 'printTime', 'spool', 'filamentLength', 'filamentVolume', 'user']
unused_fields = ["note", "id", "parameters"]
csv_header = set(fields)
for historyDetails in history_dict:
parameters = load_json(historyDetails, "parameters")
csv_header |= set(parameters.keys())
csv_header = map(lambda x: x.replace(" ", "_"), csv_header)
csv_header = rename_duplicates(fields, csv_header, prefix="g")
rearranged_header = fields[:]
for column in csv_header:
if column not in headers:
rearranged_header.append(column)
csv_header = rearranged_header
ParametersRow = namedtuple_with_defaults('TableRow', csv_header)
if sys.version_info >= (3,0):
writer = csv.writer(si, quoting=csv.QUOTE_ALL)
else:
writer = csv.writer(si, quoting=csv.QUOTE_ALL, encoding='utf-8')
writer.writerow(csv_header)
for historyDetails in history_dict:
parameters = load_json(historyDetails, "parameters")
historyDetails.update(parameters)
for key in unused_fields:
historyDetails.pop(key)
for key in ["Plastic volume", "Plastic weight", "Filament length"]:
if historyDetails.get(key, None):
historyDetails[key] = re.search(r"[\d\.]*", historyDetails[key]).group(0)
if historyDetails.get("Build time", None):
match = re.match(r"(\d+) hours (\d+) minutes", historyDetails.get("Build time", None))
historyDetails["Build time"] = (int(match.group(1)) * 60 + int(match.group(2))) * 60
parameters_row = ParametersRow(**prepare_dict(historyDetails))
writer.writerow([getattr(parameters_row, field) for field in parameters_row._fields])
response = flask.make_response(si.getvalue())
response.headers["Content-type"] = "text/csv"
response.headers["Content-Disposition"] = "attachment; filename=octoprint_print_history(extra)_export.csv"
elif exportType == 'excel':
import xlsxwriter
if sys.version_info >= (3,0):
si = BytesIO()
workbook = xlsxwriter.Workbook(si)
worksheet = workbook.add_worksheet()
for column, header in enumerate(headers):
worksheet.write(0, column, header)
for row, historyDetails in enumerate(history_dict):
for column, field in enumerate(fields):
if field == "timestamp":
value = formatTimestamp(historyDetails.get(field, '-'))
elif field == "printTime":
value = formatPrintTime(historyDetails.get(field, '-'))
else:
value = historyDetails.get(field, '-')
worksheet.write(row + 1, column, (value if value is not None else '-'))
workbook.close()
response = flask.make_response(si.getvalue())
response.headers["Content-type"] = "application/vnd.ms-excel"
response.headers["Content-Disposition"] = "attachment; filename=octoprint_print_history_export.xlsx"
return response
else:
return flask.make_response("No history file", 400)
def formatPrintTime(valueInSeconds):
if valueInSeconds is not None:
tmp = valueInSeconds
hours = int(tmp/3600)
tmp = tmp % 3600
minutes = int(tmp / 60)
tmp = tmp % 60
seconds = int(tmp)
return str(hours) + ":" + str(minutes).zfill(2) + ":" + str(seconds).zfill(2)
else:
return "-"
def formatTimestamp(millis):
import datetime
if millis is not None:
return datetime.datetime.fromtimestamp(int(millis)).strftime('%Y-%m-%d %H:%M:%S')
else:
return '-'