-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
92 lines (74 loc) · 2.6 KB
/
Copy pathapp.py
File metadata and controls
92 lines (74 loc) · 2.6 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
from flask import Flask, request, jsonify
from flask_cors import CORS
import sys
import os
# Update the import path
from services.playground import bubble_sort, insertion_sort, selection_sort, quick_sort, merge_sort, shell_sort, heap_sort
app = Flask(__name__)
# Configure CORS more permissively
CORS(app, supports_credentials=True)
# Or use specific CORS configuration
CORS(app, resources={
r"/api/*": {
"origins": "*", # Allow all origins
"methods": ["POST", "OPTIONS"],
"allow_headers": ["Content-Type", "Authorization"],
"expose_headers": ["Content-Range", "X-Content-Range"],
"supports_credentials": True,
"max_age": 120 # Cache preflight requests for 2 minutes
}
})
# Global variable to store sorting steps
sorting_steps = []
def clear_steps():
global sorting_steps
sorting_steps = []
def add_step(step):
global sorting_steps
sorting_steps.append(step)
# Modify the original print statements to store steps
def custom_print(message):
add_step(message)
@app.route('/api/sort', methods=['POST'])
def sort():
data = request.get_json()
numbers = data.get('numbers', [])
method = data.get('method', 'bubble')
# Clear previous steps
clear_steps()
# Create a copy of the numbers to avoid modifying the original
numbers_copy = numbers.copy()
# Dictionary of sorting functions
sort_functions = {
'bubble': bubble_sort,
'insertion': insertion_sort,
'selection': selection_sort,
'merge': merge_sort,
'quick': quick_sort,
'shell': shell_sort,
'heap': heap_sort
}
if method not in sort_functions:
return jsonify({'error': 'Invalid sorting method'}), 400
# Temporarily redirect print output to our custom function
import builtins
original_print = builtins.print
builtins.print = custom_print
try:
# Run the sorting algorithm
sorted_numbers = sort_functions[method](numbers_copy)
# Restore original print function
builtins.print = original_print
return jsonify({
'sorted': sorted_numbers,
'steps': sorting_steps
})
except Exception as e:
builtins.print = original_print
# Log the actual error server-side
app.logger.error(f'Sorting error: {str(e)}')
# Return generic error message to client
return jsonify({'error': 'An internal server error occurred'}), 500
if __name__ == '__main__':
debug_mode = os.environ.get('FLASK_ENV') == 'development'
app.run(debug=debug_mode, port=5001)