-
Notifications
You must be signed in to change notification settings - Fork 1
/
rest.py
315 lines (278 loc) · 12.8 KB
/
rest.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# restAPI controllers
from py4web import action, request, abort, redirect, URL, Field, response # add response to throw http error 400
from yatl.helpers import A
from .common import db, session, T, cache, auth, logger, authenticated, unauthenticated, flash # ,dbo
from pydal.restapi import RestAPI, Policy
from .settings import UPLOAD_FOLDER, SMTP_SERVER, SMTP_SENDER, SMTP_LOGIN, COMPANY_LOGO
policy = Policy()
policy.set('*','GET', authorize=True, limit=1000, allowed_patterns=['*'])
policy.set('*','POST', authorize=True)
policy.set('*','PUT', authorize=True)
policy.set('*','DELETE', authorize=True)
def rows2json (tablename,rows):
"""
Converts a list of rows from a table into a JSON string.
This function converts each row in the input list into a JSON object. If the row contains a datetime or date object,
it is converted into a string format using strftime. The format for datetime is '%Y-%m-%d %T' and for date, it is '%Y-%m-%d'.
The resulting JSON objects are concatenated into a single JSON array, which is then wrapped into a JSON object with the table name as the key.
Parameters:
tablename (str): The name of the table which the rows belong to. This is used as the key in the resulting JSON object.
rows (pandas.DataFrame or similar): A list-like object of rows to be converted into a JSON string. Each row should be a dictionary-like object where the keys correspond to the column names and the values correspond to the data in each cell.
Returns:
str: A string representation of the JSON object that contains the table data.
Raises:
TypeError: If any of the values in the rows are neither serializable as JSON nor instances of datetime.datetime or datetime.date.
"""
import datetime
import json
def date_handler(obj):
if isinstance(obj, datetime.datetime):
return obj.strftime(str(T('%Y-%m-%d %T'))) #(str(T('%d/%m/%Y %T')))
elif isinstance(obj, datetime.date):
return obj.strftime(str(T('%Y-%m-%d'))) # (str(T('%d/%m/%Y')))
else:
return False
rows = rows.as_list()
concat = '{ "'+tablename+'": ['
for row in rows:
concat = concat + json.dumps(row, default=date_handler)+","
concat = concat.strip(',')
concat = concat + ']}'
return concat
def valid_date(datestring):
"""
Check if a given date string is a valid date in the format 'YYYY-MM-DD'.
Parameters:
datestring (str): A string representing a date in the format 'YYYY-MM-DD'.
Returns:
bool: True if the datestring is a valid date, False otherwise.
Example:
>>> valid_date('2023-07-23')
True
>>> valid_date('2023-13-40')
False
"""
import datetime
try:
datetime.datetime.strptime(datestring, '%Y-%m-%d')
return True
except ValueError:
return False
@action('api/uuid', method=['GET'])
def generate_unique_id():
"""
Generate a unique ID (Universally Unique Identifier - UUID) and return it as a JSON response.
This function is a route handler used in the py4web framework to handle HTTP GET requests
targeting the 'api/uuid' endpoint.
Dependencies:
- uuid: The uuid module is used to generate the unique identifier.
- json: The json module is used to convert the response data to a JSON string.
Returns:
str: A JSON string representing the response containing the generated unique ID.
Example:
HTTP GET Request: /api/uuid
Response:
{
"unique_id": "d81d4fae-7d58-4d9f-97d4-9ba66a3e77ad"
}
"""
import uuid, json
response.headers['Content-Type'] = 'application/json;charset=UTF-8'
unique_id = str(uuid.uuid4().hex)
return json.dumps({"unique_id": unique_id})
# TODO: add header to allow CORS on distant card reader
# TODO: check if triggered_decorator is necessary
# TODO: check if sleep is necesary for allowing time to read card, or use async ?
@action('api/beid', method=['GET'])
def beid():
"""
Get informations contained in the Belgium EID card and return them as a JSON response
This function is a route handler used in the py4web framework to handle HTTP GET requests
targeting the 'api/beid' endpoint.
Dependencies:
- beid: module to read eid.
- base64: The base64 module is used to convert the image ID in base64 for export to view
Returns:
str: A JSON string representing the response contained in the EID.
"""
import json
from base64 import b64encode
from .beid import scan_readers, read_infos, triggered_decorator
from time import sleep
r = scan_readers()[0]
infos_json = {}
response.headers['Content-Type'] = 'application/json;charset=UTF-8'
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
try:
# sleep(2)
infos = read_infos(r, read_photo=True)
infos['photo'] = b64encode(infos['photo']).decode('utf8')
except Exception as e:
infos = { 'results': 'cannot read card', 'erreur': e.args}
infos_json = json.dumps(infos)
return infos_json
# TODO: authentification
# TODO: correct password PUT -> does not work
@action('api/<tablename>/', method=['GET','POST','PUT']) # PUT ok
@action('api/<tablename>/<rec_id>', method=['GET','PUT','DELETE']) # delete OK get OK post OK
@action.uses(db,session)
def api(tablename, rec_id=None):
"""
API endpoint for GET, POST, PUT, DELETE a row in a table
Args:
tablename (str): name of the table
rec_id (int): id of the row for PUT or DELETE
Returns:
str: a JSON response from py4web
Raises:
ValueError: 400 values are not valid
Exemples:
http://localhost:8000/'+APP_NAME+'/api/phone?id_auth_user=2&@lookup=phone:id_auth_user -> get phone from auth_user_id
http://localhost:8000/'+APP_NAME+'/api/phone?id_auth_user=2&@lookup=identity!:id_auth_user[first_name,last_name] -> denormalised (flat)
"""
db.phone.id_auth_user.writable= db.address.id_auth_user.writable = True
db.phone.id_auth_user.readable = db.address.id_auth_user.readable = True
db.auth_user.password.readable = True
db.auth_user.password.writable = True
db.address.created_by.readable = db.address.modified_by.readable = db.address.created_on.readable = db.address.modified_on.readable = db.address.id_auth_user.readable = True
db.auth_user.created_by.readable = db.auth_user.modified_by.readable = db.auth_user.created_on.readable = db.auth_user.modified_on.readable = True
db.phone.created_by.readable = db.phone.modified_by.readable = db.phone.created_on.readable = db.phone.modified_on.readable = db.phone.id_auth_user.readable = True
db.worklist.created_by.readable = db.worklist.modified_by.readable = db.worklist.created_on.readable = db.worklist.modified_on.readable = db.worklist.id_auth_user.readable = True
db.photo_id.created_by.readable = db.photo_id.modified_by.readable = db.photo_id.created_on.readable = db.photo_id.modified_on.readable = db.photo_id.id_auth_user.readable = True
if (tablename == "auth_user" and request.method == "PUT" and "id" in request.json): # check if email, password, first_name, last_name
# request.json["password"]=db(db.auth_user.id == 1).select(db.auth_user.password).first()[0]
row=db(db.auth_user.id == request.json["id"]).select(db.auth_user.ALL).first()
if "password" not in request.json:
request.json["password"]= row.password
if "email" not in request.json:
request.json["email"]= row.email
if "first_name" not in request.json:
request.json["first_name"]= row.first_name
if "last_name" not in request.json:
request.json["last_name"]= row.last_name
if "username" not in request.json:
request.json["username"]= row.username
try:
json_resp = RestAPI(db,policy)(request.method,tablename,rec_id,request.GET,request.json)
# json_resp RestAPI(db,policy)(request.method,tablename,rec_id,request.GET,request.POST)
db.commit()
return json_resp
except ValueError:
response.status = 400
return
@action('octopus/api/<tablename>/', method=['GET','POST','PUT']) # PUT ok
@action('octopus/api/<tablename>/<rec_id>', method=['GET','PUT','DELETE']) # delete OK get OK post OK
@action.uses(db)
def octopus(tablename, rec_id=None):
try:
json_resp = RestAPI(dbo,policy)(request.method,tablename,rec_id,request.GET,request.json)
db.commit()
return json_resp
except ValueError:
response.status = 400
return
@action('upload', method=['POST'])
def do_upload():
import os, json, bottle
response = bottle.response
response.headers['Content-Type'] = 'application/json;charset=UTF-8'
file = request.files.get('file')
re_dict = { 'filename': file.filename }
name, ext = os.path.splitext(file.filename)
if ext not in ('.png','.jpg','.jpeg','.webp','.pdf'):
re_dict.update({ 'status' : 'error', 'error' : 'File extension not allowed.'})
return json.dumps(re_dict)
try:
file.save(UPLOAD_FOLDER)
re_dict.update({ 'status' : 'saved'})
except Exception as e:
re_dict.update({ 'status' : 'error', 'error' : e.args[0] })
re = json.dumps(re_dict)
return re
@action('api/email/send', method=['POST'])
def send_email():
"""
Send an email using SMTP server.
Parameters:
- recipient: The email address of the recipient.
- title: The subject of the email.
- content: The main content/body of the email.
- company_logo: URL or path to the company logo.
- sender_name: The name of the sender.
- sender_quality: The title or position of the sender.
Returns:
- JSON-formatted response indicating the result of the email sending operation.
"""
import smtplib
import json
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
payload = request.json
sender_name , sender_quality = 'Mamisoa Andriantafika', 'MD, FEBO'
title, content = 'Informations | Centre Médical Bruxelles-Schuman', 'content'
username, password = SMTP_LOGIN.split('::')
smtp_server , port = SMTP_SERVER.split(':')
company_logo = COMPANY_LOGO
if 'recipient' not in payload:
return json.dumps('{ "status": "error", "message": "No recipient"}')
for key in request.json:
if key == 'recipient':
recipient = payload['recipient']
if key == 'title':
title = payload['title']
if key == 'content':
content = payload['content']
if key == 'sender_name':
sender_name = payload['sender_name']
# HTML template
html_template = f"""
<html>
<body>
<div>{content}</div>
<br>
<p>Cordialement,<br>Vriendelijke groeten,<br>Best regards,</p>
<table>
<tr>
<td><img src="{company_logo}" alt="Company Logo" style="max-width: 100px;"></td>
<td>
<p>{sender_name}<br>{sender_quality}</p>
</td>
</tr>
</table>
<hr style="border: none; border-top: 1px solid #ccc; margin: 20px 0;">
<p style="font-size: 0.8em; color: #666;">
The contents of this e-mail are intended for the named addressee only. It contains information which may be confidential and which may also be privileged. Any non-conform use, dissemination or disclosure of this message is prohibited. If you received it in error, please notify us immediately and then destroy it.
</p>
</body>
</html>
"""
# Create the MIMEText object
msg = MIMEMultipart("alternative")
msg["Subject"] = title
msg["From"] = username
msg["To"] = recipient
# Attach the HTML content to the email
msg.attach(MIMEText(html_template, "html"))
try:
# Send the email
with smtplib.SMTP(smtp_server, port) as server:
server.starttls() # Secure the connection using TLS
server.login(username, password)
server.sendmail(username, recipient, msg.as_string())
# If the email is sent successfully, return a success response
response = {
"status": "success",
"message": "Email sent successfully.",
"title" : title,
"content" : content,
"recipient" : recipient
}
except Exception as e:
# If there's an error, return an error response
response = {
"status": "error",
"message": str(e)
}
return json.dumps(response)