forked from AllonKleinLab/SPRING_dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflask_server.py
More file actions
91 lines (68 loc) · 2.37 KB
/
flask_server.py
File metadata and controls
91 lines (68 loc) · 2.37 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
import argparse
import os
import subprocess
from flask import Flask, request, abort, send_from_directory
parser = argparse.ArgumentParser(
description='Start Flask server with optional debugging and port specification.')
parser.add_argument('-d', '--debug', action='store_true',
help='run the server in debug mode')
DEFAULT_PORT = 8000
parser.add_argument('-p', '--port', type=int, default=DEFAULT_PORT,
help='set the port for the server')
args = parser.parse_args()
app = Flask(__name__)
this_directory = os.path.dirname(os.path.abspath(__file__))
ALLOWED_EXTENSIONS = {
'txt',
'json',
'csv',
'js',
'css',
'html',
'png',
'svg',
'gif',
'map',
'ico',
}
SCRIPTS_FOLDER = "cgi-bin"
@app.route('/<path:file_path>', methods=['GET'])
def serve_file(file_path):
# Don't allow paths which exit this directory
if '..' in file_path:
abort(400)
# Extract the file extension and check if it's allowed
file_extension = os.path.splitext(file_path)[1].lstrip('.').lower()
if file_extension not in ALLOWED_EXTENSIONS:
print(f"400 Unsupported File Extension: {file_extension}")
abort(400)
# Check if the file exists
full_path = os.path.join(this_directory, file_path)
if not os.path.isfile(full_path):
abort(404)
# Serve the file content
return send_from_directory(this_directory, file_path)
@app.route(f'/{SCRIPTS_FOLDER}/<script_name>.py', methods=['POST'])
def run_script(script_name):
# Don't allow paths which exit this directory
if '..' in script_name:
abort(400)
# Check if the script exists
script_path = os.path.join(
this_directory, SCRIPTS_FOLDER, script_name) + ".py"
if not os.path.isfile(script_path):
abort(404)
# Convert form data to a string
form_data_str = '&'.join(
f"{key}={value}" for key, value in request.form.items())
# Execute the script
try:
result = subprocess.run(
['python', script_path], input=form_data_str, text=True, capture_output=True, check=True)
return result.stdout
except subprocess.CalledProcessError as e:
abort(500, description=e.stderr)
def run_server(port: int = DEFAULT_PORT, debug: bool = False):
app.run(port=port, debug=debug)
if __name__ == '__main__':
run_server(port=args.port, debug=args.debug)