Passed
Push — master ( 17dcd8...c09fbc )
by Guangyu
01:53 queued 10s
created

AdvancedReportItem.on_options()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
from datetime import datetime, timedelta, timezone
5
import base64
6
import sys
7
import config
8
9
10
class AdvancedReportCollection:
11
    @staticmethod
12
    def __init__():
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    ####################################################################################################################
20
    # PROCEDURES
21
    # Step 1: valid parameters
22
    # Step 2: query advanced reports
23
    # Step 3: construct the result
24
    ####################################################################################################################
25
    @staticmethod
26
    def on_get(req, resp):
27
        print(req.params)
28
        reporting_start_datetime_local = req.params.get('reportingperiodstartdatetime')
29
        reporting_end_datetime_local = req.params.get('reportingperiodenddatetime')
30
31
        ################################################################################################################
32
        # Step 1: valid parameters
33
        ################################################################################################################
34
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
35
        if config.utc_offset[0] == '-':
36
            timezone_offset = -timezone_offset
37
38
        if reporting_start_datetime_local is None:
39
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
40
                                   description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
41
        else:
42
            reporting_start_datetime_local = str.strip(reporting_start_datetime_local)
43
            try:
44
                reporting_start_datetime_utc = datetime.strptime(reporting_start_datetime_local,
45
                                                                 '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
46
                    timedelta(minutes=timezone_offset)
47
            except ValueError:
48
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
49
                                       description="API.INVALID_REPORTING_PERIOD_BEGINS_DATETIME")
50
51
        if reporting_end_datetime_local is None:
52
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
53
                                   description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
54
        else:
55
            reporting_end_datetime_local = str.strip(reporting_end_datetime_local)
56
            try:
57
                reporting_end_datetime_utc = datetime.strptime(reporting_end_datetime_local,
58
                                                               '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \
59
                    timedelta(minutes=timezone_offset)
60
            except ValueError:
61
                raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
62
                                       description="API.INVALID_REPORTING_PERIOD_ENDS_DATETIME")
63
64
        if reporting_start_datetime_utc >= reporting_end_datetime_utc:
65
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
66
                                   description='API.INVALID_REPORTING_PERIOD_ENDS_DATETIME')
67
68
        ################################################################################################################
69
        # Step 2: query advanced reports
70
        ################################################################################################################
71
72
        cnx_reporting = mysql.connector.connect(**config.myems_reporting_db)
73
        cursor_reporting = cnx_reporting.cursor(dictionary=True)
74
75
        query = (" SELECT id, file_name, uuid, create_datetime_utc, file_type, file_object "
76
                 " FROM tbl_reports_files "
77
                 " WHERE create_datetime_utc >= %s AND create_datetime_utc < %s "
78
                 " ORDER BY create_datetime_utc desc ")
79
        cursor_reporting.execute(query, (reporting_start_datetime_utc, reporting_end_datetime_utc))
80
        rows = cursor_reporting.fetchall()
81
        if cursor_reporting:
82
            cursor_reporting.close()
83
        if cnx_reporting:
84
            cnx_reporting.disconnect()
85
86
        ################################################################################################################
87
        # Step 3: construct the result
88
        ################################################################################################################
89
        result = list()
90
        if rows is not None and len(rows) > 0:
91
            for row in rows:
92
                # Base64 encode the bytes
93
                base64_encoded_data = base64.b64encode(row['file_object'])
94
                # get the Base64 encoded data using human-readable characters.
95
                base64_message = base64_encoded_data.decode('utf-8')
96
                create_datetime_local = row['create_datetime_utc'].replace(tzinfo=None) + \
97
                    timedelta(minutes=timezone_offset)
98
                meta_result = {"id": row['id'],
99
                               "file_name": row['file_name'],
100
                               "uuid": row['uuid'],
101
                               "create_datetime_local": create_datetime_local.isoformat(),
102
                               "file_type": row['file_type'],
103
                               "file_size_bytes": sys.getsizeof(row['file_object']),
104
                               "file_bytes_base64": base64_message}
105
                result.append(meta_result)
106
107
        resp.body = json.dumps(result)
108
109
110
class AdvancedReportItem:
111
    @staticmethod
112
    def __init__():
113
        pass
114
115
    @staticmethod
116
    def on_options(req, resp, id_):
117
        resp.status = falcon.HTTP_200
118
119
    @staticmethod
120
    def on_get(req, resp, id_):
121
        if not id_.isdigit() or int(id_) <= 0:
122
            raise falcon.HTTPError(falcon.HTTP_400,
123
                                   title='API.BAD_REQUEST',
124
                                   description='API.INVALID_ADVANCED_REPORT_ID')
125
126
        cnx_reporting = mysql.connector.connect(**config.myems_reporting_db)
127
        cursor_reporting = cnx_reporting.cursor(dictionary=True)
128
129
        query = (" SELECT id, file_name, uuid, create_datetime_utc, file_type, file_object "
130
                 " FROM tbl_reports_files "
131
                 " WHERE id = %s ")
132
        cursor_reporting.execute(query, (id_,))
133
        row = cursor_reporting.fetchone()
134
        if cursor_reporting:
135
            cursor_reporting.close()
136
        if cnx_reporting:
137
            cnx_reporting.disconnect()
138
139
        if row is None:
140
            raise falcon.HTTPError(falcon.HTTP_404,
141
                                   title='API.NOT_FOUND',
142
                                   description='API.ADVANCED_REPORT_NOT_FOUND')
143
144
        # Base64 encode the bytes
145
        base64_encoded_data = base64.b64encode(row['file_object'])
146
        # get the Base64 encoded data using human-readable characters.
147
        base64_message = base64_encoded_data.decode('utf-8')
148
149
        result = {"id": row['id'],
150
                  "file_name": row['file_name'],
151
                  "uuid": row['uuid'],
152
                  "create_datetime":
153
                  row['create_datetime_utc'].replace(tzinfo=timezone.utc).timestamp() * 1000,
154
                  "file_type": row['file_type'],
155
                  "file_bytes_base64": base64_message}
156
        resp.body = json.dumps(result)
157
158
    @staticmethod
159
    def on_delete(req, resp, id_):
160
        if not id_.isdigit() or int(id_) <= 0:
161
            raise falcon.HTTPError(falcon.HTTP_400,
162
                                   title='API.BAD_REQUEST',
163
                                   description='API.INVALID_ADVANCED_REPORT_ID')
164
165
        cnx_reporting = mysql.connector.connect(**config.myems_reporting_db)
166
        cursor_reporting = cnx_reporting.cursor(dictionary=True)
167
168
        cursor_reporting.execute(" SELECT id "
169
                                 " FROM tbl_reports_files "
170
                                 " WHERE id = %s ", (id_,))
171
        if cursor_reporting.fetchone() is None:
172
            cursor_reporting.close()
173
            cnx_reporting.disconnect()
174
            raise falcon.HTTPError(falcon.HTTP_404,
175
                                   title='API.NOT_FOUND',
176
                                   description='API.ADVANCED_REPORT_NOT_FOUND')
177
178
        cursor_reporting.execute(" DELETE FROM tbl_reports_files "
179
                                 " WHERE id = %s ", (id_,))
180
        cnx_reporting.commit()
181
182
        if cursor_reporting:
183
            cursor_reporting.close()
184
        if cnx_reporting:
185
            cnx_reporting.disconnect()
186
187
        resp.status = falcon.HTTP_204
188