Passed
Push — master ( 14eaf2...8a3da8 )
by Guangyu
07:24 queued 12s
created

WechatMessageCollection.__init__()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 4
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 3
dl 4
loc 4
rs 10
c 0
b 0
f 0
cc 1
nop 0
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
from datetime import datetime, timedelta, timezone
6
from core.useractivity import user_logger, access_control
7
8
9 View Code Duplication
class WechatMessageCollection(object):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
10
    @staticmethod
11
    def __init__():
12
        """"Initializes WechatMessageCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp, startdate, enddate):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp, startdate, enddate):
21
        access_control(req)
22
        try:
23
            start_datetime_local = datetime.strptime(startdate, '%Y-%m-%d')
24
        except Exception:
25
            raise falcon.HTTPError(falcon.HTTP_400,
26
                                   title='API.BAD_REQUEST',
27
                                   description='API.INVALID_START_DATE_FORMAT')
28
        try:
29
            end_datetime_local = datetime.strptime(enddate, '%Y-%m-%d')
30
        except Exception:
31
            raise falcon.HTTPError(falcon.HTTP_400,
32
                                   title='API.BAD_REQUEST',
33
                                   description='API.INVALID_END_DATE_FORMAT')
34
35
        timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6])
36
        if config.utc_offset[0] == '-':
37
            timezone_offset = -timezone_offset
38
39
        start_datetime_utc = start_datetime_local.replace(tzinfo=timezone.utc)
40
        start_datetime_utc -= timedelta(minutes=timezone_offset)
41
42
        end_datetime_utc = end_datetime_local.replace(tzinfo=timezone.utc)
43
        end_datetime_utc -= timedelta(minutes=timezone_offset)
44
        end_datetime_utc += timedelta(days=1)
45
46
        if start_datetime_utc >= end_datetime_utc:
47
            raise falcon.HTTPError(falcon.HTTP_400,
48
                                   title='API.BAD_REQUEST',
49
                                   description='API.START_DATETIME_MUST_BE_EARLIER_THAN_END_DATETIME')
50
        cnx = mysql.connector.connect(**config.myems_fdd_db)
51
        cursor = cnx.cursor()
52
53
        query = (" SELECT id, recipient_name, recipient_openid, message_template_id, "
54
                 "        message_data, created_datetime_utc, scheduled_datetime_utc, "
55
                 "        acknowledge_code, status "
56
                 " FROM tbl_wechat_messages_outbox "
57
                 " WHERE created_datetime_utc >= %s AND created_datetime_utc < %s "
58
                 " ORDER BY created_datetime_utc DESC ")
59
        cursor.execute(query, (start_datetime_utc, end_datetime_utc))
60
        rows = cursor.fetchall()
61
62
        if cursor:
63
            cursor.close()
64
        if cnx:
65
            cnx.disconnect()
66
67
        result = list()
68
        if rows is not None and len(rows) > 0:
69
            for row in rows:
70
                meta_result = {"id": row[0],
71
                               "recipient_name": row[1],
72
                               "recipient_openid": row[2],
73
                               "message_template_id": row[3],
74
                               "message_data": row[4],
75
                               "created_datetime_utc": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
76
                               "scheduled_datetime_utc": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
77
                               "acknowledge_code": row[7],
78
                               "status": row[8]}
79
                result.append(meta_result)
80
81
        resp.text = json.dumps(result)
82
83
84 View Code Duplication
class WechatMessageItem:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
85
    @staticmethod
86
    def __init__():
87
        """"Initializes WechatMessageItem"""
88
        pass
89
90
    @staticmethod
91
    def on_options(req, resp, id_):
92
        resp.status = falcon.HTTP_200
93
94
    @staticmethod
95
    def on_get(req, resp, id_):
96
        access_control(req)
97
        if not id_.isdigit() or int(id_) <= 0:
98
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
99
                                   description='API.INVALID_WECHAT_MESSAGE_ID')
100
101
        cnx = mysql.connector.connect(**config.myems_fdd_db)
102
        cursor = cnx.cursor()
103
104
        query = (" SELECT id, recipient_name, recipient_openid, message_template_id, "
105
                 "        message_data, created_datetime_utc, scheduled_datetime_utc, "
106
                 "        acknowledge_code, status "
107
                 " FROM tbl_wechat_messages_outbox "
108
                 " WHERE id = %s ")
109
        cursor.execute(query, (id_,))
110
        row = cursor.fetchone()
111
112
        if cursor:
113
            cursor.close()
114
        if cnx:
115
            cnx.disconnect()
116
117
        if row is None:
118
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
119
                                   description='API.WECHAT_MESSAGE_NOT_FOUND')
120
121
        result = {"id": row[0],
122
                  "recipient_name": row[1],
123
                  "recipient_openid": row[2],
124
                  "recipient_template_id": row[3],
125
                  "message_data": row[4],
126
                  "created_datetime_utc": row[5].timestamp() * 1000 if isinstance(row[5], datetime) else None,
127
                  "scheduled_datetime_utc": row[6].timestamp() * 1000 if isinstance(row[6], datetime) else None,
128
                  "acknowledge_code": row[7],
129
                  "status": row[8]}
130
131
        resp.text = json.dumps(result)
132
133
    @staticmethod
134
    @user_logger
135
    def on_delete(req, resp, id_):
136
        access_control(req)
137
        if not id_.isdigit() or int(id_) <= 0:
138
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
139
                                   description='API.INVALID_WECHAT_MESSAGE_ID')
140
141
        cnx = mysql.connector.connect(**config.myems_fdd_db)
142
        cursor = cnx.cursor()
143
144
        cursor.execute(" SELECT id "
145
                       " FROM tbl_wechat_messages_outbox "
146
                       " WHERE id = %s ", (id_,))
147
        row = cursor.fetchone()
148
149
        if row is None:
150
            if cursor:
151
                cursor.close()
152
            if cnx:
153
                cnx.disconnect()
154
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
155
                                   description='API.WECHAT_MESSAGE_NOT_FOUND')
156
157
        cursor.execute(" DELETE FROM tbl_wechat_messages_outbox WHERE id = %s ", (id_,))
158
        cnx.commit()
159
160
        if cursor:
161
            cursor.close()
162
        if cnx:
163
            cnx.disconnect()
164
165
        resp.status = falcon.HTTP_204
166