Conditions | 31 |
Total Lines | 129 |
Code Lines | 98 |
Lines | 16 |
Ratio | 12.4 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
Complex classes like core.notification.NotificationCollection.on_get() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import falcon |
||
17 | @staticmethod |
||
18 | def on_get(req, resp): |
||
19 | status = req.params.get('status') |
||
20 | start_datetime_local = req.params.get('startdatetime') |
||
21 | end_datetime_local = req.params.get('enddatetime') |
||
22 | if status is not None: |
||
23 | status = str.strip(status) |
||
24 | if status not in ['new', 'read', 'archived']: |
||
25 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', description='API.INVALID_STATUS') |
||
26 | |||
27 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
28 | if config.utc_offset[0] == '-': |
||
29 | timezone_offset = -timezone_offset |
||
30 | start_datetime_utc = None |
||
31 | if start_datetime_local is not None and len(str.strip(start_datetime_local)) > 0: |
||
32 | start_datetime_local = str.strip(start_datetime_local) |
||
33 | try: |
||
34 | start_datetime_utc = datetime.strptime(start_datetime_local, |
||
35 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
36 | timedelta(minutes=timezone_offset) |
||
37 | except ValueError: |
||
38 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
39 | description="API.INVALID_START_DATETIME") |
||
40 | |||
41 | end_datetime_utc = None |
||
42 | if end_datetime_local is not None and len(str.strip(end_datetime_local)) > 0: |
||
43 | end_datetime_local = str.strip(end_datetime_local) |
||
44 | try: |
||
45 | end_datetime_utc = datetime.strptime(end_datetime_local, |
||
46 | '%Y-%m-%dT%H:%M:%S').replace(tzinfo=timezone.utc) - \ |
||
47 | timedelta(minutes=timezone_offset) |
||
48 | except ValueError: |
||
49 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
50 | description="API.INVALID_END_DATETIME") |
||
51 | |||
52 | if start_datetime_utc is not None and end_datetime_utc is not None and \ |
||
53 | start_datetime_utc >= end_datetime_utc: |
||
54 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
55 | description='API.INVALID_END_DATETIME') |
||
56 | |||
57 | # Verify User Session |
||
58 | cookie_dict = dict() |
||
59 | cookies = req.headers['COOKIE'].split(';') |
||
60 | for cookie in cookies: |
||
61 | kv = cookie.split('=') |
||
62 | cookie_dict[str.strip(kv[0])] = str.strip(kv[1]) |
||
63 | |||
64 | if cookie_dict.get('user_uuid') is None or cookie_dict.get('token') is None: |
||
65 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
66 | description='API.INVALID_COOKIES_PLEASE_RE_LOGIN') |
||
67 | |||
68 | cnx = mysql.connector.connect(**config.myems_user_db) |
||
69 | cursor = cnx.cursor() |
||
70 | |||
71 | query = (" SELECT utc_expires " |
||
72 | " FROM tbl_sessions " |
||
73 | " WHERE user_uuid = %s AND token = %s") |
||
74 | cursor.execute(query, (cookie_dict.get('user_uuid'), cookie_dict.get('token'),)) |
||
75 | row = cursor.fetchone() |
||
76 | |||
77 | View Code Duplication | if row is None: |
|
|
|||
78 | if cursor: |
||
79 | cursor.close() |
||
80 | if cnx: |
||
81 | cnx.disconnect() |
||
82 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
83 | description='API.INVALID_SESSION_PLEASE_RE_LOGIN') |
||
84 | else: |
||
85 | utc_expires = row[0] |
||
86 | if datetime.utcnow() > utc_expires: |
||
87 | if cursor: |
||
88 | cursor.close() |
||
89 | if cnx: |
||
90 | cnx.disconnect() |
||
91 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
92 | description='API.USER_SESSION_TIMEOUT') |
||
93 | |||
94 | cursor.execute(" SELECT id " |
||
95 | " FROM tbl_users " |
||
96 | " WHERE uuid = %s ", |
||
97 | (cookie_dict.get('user_uuid'),)) |
||
98 | row = cursor.fetchone() |
||
99 | if row is None: |
||
100 | if cursor: |
||
101 | cursor.close() |
||
102 | if cnx: |
||
103 | cnx.disconnect() |
||
104 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
105 | description='API.INVALID_USER_PLEASE_RE_LOGIN') |
||
106 | else: |
||
107 | user_id = row[0] |
||
108 | |||
109 | # get notifications |
||
110 | if status is None: |
||
111 | query = (" SELECT id, created_datetime_utc, status, subject, message, url " |
||
112 | " FROM tbl_notifications " |
||
113 | " WHERE user_id = %s AND " |
||
114 | " created_datetime_utc >= %s AND created_datetime_utc < %s " |
||
115 | " ORDER BY created_datetime_utc DESC ") |
||
116 | cursor.execute(query, (user_id, start_datetime_utc, end_datetime_utc)) |
||
117 | else: |
||
118 | query = (" SELECT id, created_datetime_utc, status, subject, message, url " |
||
119 | " FROM tbl_notifications " |
||
120 | " WHERE user_id = %s AND " |
||
121 | " created_datetime_utc >= %s AND created_datetime_utc < %s AND " |
||
122 | " status = %s " |
||
123 | " ORDER BY created_datetime_utc DESC ") |
||
124 | cursor.execute(query, (user_id, start_datetime_utc, end_datetime_utc, status)) |
||
125 | rows = cursor.fetchall() |
||
126 | |||
127 | if cursor: |
||
128 | cursor.close() |
||
129 | if cnx: |
||
130 | cnx.disconnect() |
||
131 | |||
132 | result = list() |
||
133 | if rows is not None and len(rows) > 0: |
||
134 | for row in rows: |
||
135 | meta_result = {"id": row[0], |
||
136 | "created_datetime": |
||
137 | (row[1] + |
||
138 | timedelta(hours=int(config.utc_offset[1:3]))).strftime('%Y-%m-%dT%H:%M:%S'), |
||
139 | "status": row[2], |
||
140 | "subject": row[3], |
||
141 | "message": row[4], |
||
142 | "url": row[5]} |
||
143 | result.append(meta_result) |
||
144 | |||
145 | resp.body = json.dumps(result) |
||
146 | |||
420 |