-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbackend.py
More file actions
335 lines (260 loc) · 10.4 KB
/
backend.py
File metadata and controls
335 lines (260 loc) · 10.4 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import os
import json
import traceback
from flask import Flask, request, jsonify, Response, stream_with_context, session
from flask_cors import CORS
from dotenv import load_dotenv
import io
from contextlib import redirect_stdout, redirect_stderr
# Initialization Code
from datetime import datetime
import numpy as np
import gc
import pathsim, pathsim_chem
print(f"PathSim {pathsim.__version__} loaded successfully")
STREAMING_STEP_EXPR = "_step_streaming_gen()"
NAMESPACE_LIFETIME = 60* 60 * 1000 # A namespace will persist for a maximum of 1 hour before deletion
_clean_globals = set(globals().keys())
'''
The Flask web server would not be initialized simultaneously with the SvelteKit website since the latter is statically generated,
rather there would be some type of deployment of this application such that it could receive requests from
"https://view.pathsim.org" (which I think is already encapsualted by the "*" in the CORS.resources.options parameter)
'''
load_dotenv()
server_namespaces = {}
app = Flask(__name__, static_folder="../static", static_url_path="")
# app.secret_key = os.getenv("SECRET_KEY")
# app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
# app.config["SESSION_PERMANENT"] = False
# app.config["SESSION_TYPE"] = 'filesystem'
app.config.update(
SECRET_KEY=os.getenv("SECRET_KEY"), # Required for session
SESSION_COOKIE_SAMESITE='None',
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
)
# app.config["SESSION_SERIALIZATION_FORMAT"] = 'json'
# app.config["SESSION_CACHELIB"] = FileSystemCache(threshold=500, cache_dir="/sessions"),
# Session(app)f
if os.getenv("FLASK_ENV") == "production":
CORS(app,
resources={
r"/*": {
"origins": ["*"],
"methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"]
}
}, supports_credentials=True)
else:
print("We are not in production...")
CORS(
app,
resources={
r"/*": {""
"origins": ["http://localhost:5173", "http://localhost:3000"]
}
},
supports_credentials=True
)
@app.route("/initialize", methods=["GET"])
def initalize():
session_id = None
if "id" in session:
session_id = session["id"]
app.logger.info("We already have a session ID it is...")
app.logger.info(session_id)
else:
app.logger.info("Making a session id...")
session_id = str(os.urandom(12))
app.logger.info("Made the id: ")
app.logger.info(session_id)
session["id"] = session_id
server_namespaces[session_id] = {
"namespace": {},
"lifetime": NAMESPACE_LIFETIME,
"created": datetime.now()
}
try:
return jsonify({
"success": True,
"id": session_id
})
except Exception as e:
return jsonify({
"success": False,
"error": e
}), 400
@app.route("/idCheck", methods=["GET"])
def idCheck():
session_id = None
if "id" in session:
session_id = session["id"]
return jsonify({ "success": True, "id": session_id })
@app.route("/namespaceCheck", methods=["GET"])
def namespaceCheck():
namespace = {}
session_id = None
if "id" in session:
app.logger.info("The id exists...")
session_id = session["id"]
if session_id in server_namespaces:
app.logger.info("Found an associated namespace...")
namespace = server_namespaces[session["id"]]["namespace"]
keys = ""
if isinstance(namespace, dict):
for k in server_namespaces.keys():
keys += k + ", "
return jsonify({ "success": True, "namespace_keys": keys})
# Execute Python route copied from the previous repository
@app.route("/execute-code", methods=["POST"])
def execute_code():
"""Execute Python code and returns nothing."""
try:
data = request.json
code = data.get("code", "")
if not code.strip():
return jsonify({"success": False, "error": "No code provided"}), 400
# Capture stdout and stderr
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
user_namespace = {}
app.logger.info("Session: ", session)
app.logger.info("Session ID: ", session["id"])
if "id" in session:
user_namespace = server_namespaces[session["id"]]["namespace"]
try:
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
exec(code, user_namespace)
app.logger.info("User Namespace: ", user_namespace)
if "id" in session:
server_namespaces[session["id"]]["namespace"] = user_namespace
# Capture any output
output = stdout_capture.getvalue()
error_output = stderr_capture.getvalue()
if error_output:
return jsonify({"success": False, "error": error_output})
return jsonify(
{
"success": True,
"output": output,
}
)
except SyntaxError as e:
return jsonify({"success": False, "error": f"Syntax Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Runtime Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Server error: {str(e)}"}), 500
@app.route("/evaluate-expression", methods=["POST"])
def evaluate_expression():
"Evaluates Python expression and returns result"
try:
data = request.json
expr = data.get("expr")
if not expr.strip():
return jsonify({"success": False, "error": "No Python expression provided"}), 400
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
user_namespace = {}
if "id" in session:
user_namespace = server_namespaces[session["id"]]["namespace"]
try:
result = ""
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
result = eval(expr, user_namespace)
app.logger.info("User Namespace: ", user_namespace)
if "id" in session:
server_namespaces[session["id"]]["namespace"] = user_namespace
# Capture any output
output = stdout_capture.getvalue()
error_output = stderr_capture.getvalue()
if error_output:
return jsonify({"success": False, "error": error_output})
return jsonify(
{
"success": True,
"result": result,
"output": output
}
)
except SyntaxError as e:
return jsonify({"success": False, "error": f"Syntax Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Runtime Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Server error: {str(e)}"}), 500
@app.route("/traceback", methods=["GET"])
def check_traceback():
try:
traceback_text = traceback.format_exc()
return jsonify({"success": True, "traceback": traceback_text})
except Exception as e:
return jsonify({"success": False, "error": f"Server-side error: {e}"})
@app.route("/streamData", methods=["POST", "GET"])
def stream_data():
def generate(expr):
# Capture stdout and stderror
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
user_namespace = {}
if "id" in session:
user_namespace = server_namespaces[session["id"]]["namespace"]
isDone = False
while not isDone:
result = " "
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
result = eval(expr, user_namespace)
app.logger.info("User Namespace: ", user_namespace)
if "id" in session:
server_namespaces[session["id"]]["namespace"] = user_namespace
# Capture any output
output = stdout_capture.getvalue()
error_output = stderr_capture.getvalue()
if error_output:
return jsonify({"success": False, "error": error_output})
# Directly responding with a Flask Response object (as jsonify(...) does) doesn't work
# so we need to use the json.dumps(...) function to return a string so that it can pass into
# stream_with_context(...)
yield json.dumps(
{
"success": True,
"result": result,
"output": output
}
)
if result["done"]:
isDone = True
try:
method = request.method
expr = STREAMING_STEP_EXPR
if method == "POST":
data = request.json
expr = data.get("expr")
try:
return Response(stream_with_context(generate(expr)), content_type='application/json')
except SyntaxError as e:
return jsonify({"success": False, "error": f"Syntax Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Runtime Error: {str(e)}"}), 400
except Exception as e:
return jsonify({"success": False, "error": f"Server error: {str(e)}"}), 500
# Global error handler to ensure all errors return JSON
@app.errorhandler(Exception)
def handle_exception(e):
"""Global exception handler to ensure JSON responses."""
import traceback
from werkzeug.exceptions import HTTPException
error_details = traceback.format_exc()
print(f"Unhandled exception: {error_details}")
# For HTTP exceptions, return a cleaner response
if isinstance(e, HTTPException):
return jsonify(
{"success": False, "error": f"{e.name}: {e.description}"}
), e.code
# For all other exceptions, return a generic JSON error
return jsonify({"success": False, "error": f"Internal server error: {str(e)}"}), 500
if __name__ == "__main__":
port = int(os.getenv("PORT", 8000))
print("Hello there...our port is: ", port)
print("Application Configuration: ", app.config)
app.run(host="0.0.0.0", port=port, debug=os.getenv("FLASK_ENV") != "production")