-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtempCodeRunnerFile.py
More file actions
78 lines (66 loc) · 3 KB
/
tempCodeRunnerFile.py
File metadata and controls
78 lines (66 loc) · 3 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
import json
import os
from werkzeug.wrappers import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.serving import run_simple
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.exceptions import NotFound
from werkzeug.static import SharedDataMiddleware
class ApiApplication:
"""A simple WSGI application that provides a JSON API."""
def __init__(self):
self.url_map = Map([
Rule('/data', endpoint='get_data', methods=['GET']),
Rule('/data', endpoint='add_data', methods=['POST']),
])
# Sample in-memory data store
self.sample_data = [
{"id": 1, "item": "Learn Python"},
{"id": 2, "item": "Learn Werkzeug"},
{"id": 3, "item": "Build a frontend"},
]
def dispatch_request(self, request):
adapter = self.url_map.bind_to_environ(request.environ)
try:
endpoint, values = adapter.match()
return getattr(self, f'on_{endpoint}')(request, **values)
except NotFound:
return Response("API endpoint not found", status=404)
except Exception as e:
return Response(f"Server error: {e}", status=500)
def on_get_data(self, request):
return Response(json.dumps(self.sample_data), mimetype='application/json')
def on_add_data(self, request):
if request.mimetype == 'application/json':
new_item_data = json.loads(request.data)
if 'item' in new_item_data:
new_id = max(d['id'] for d in self.sample_data) + 1 if self.sample_data else 1
new_item = {"id": new_id, "item": new_item_data['item']}
self.sample_data.append(new_item)
return Response(json.dumps(new_item), status=201, mimetype='application/json')
return Response(json.dumps({'error': 'Invalid data'}), status=400, mimetype='application/json')
def wsgi_app(self, environ, start_response):
request = Request(environ)
response = self.dispatch_request(request)
return response(environ, start_response)
def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
def create_app():
# API application at /api
api_app = ApiApplication()
# Static file serving for the frontend.
# This will serve files from the 'frontend' directory.
static_app = SharedDataMiddleware(Response('Not Found', status=404), {
'/': os.path.join(os.path.dirname(__file__), 'frontend')
})
# Use a dispatcher to route requests.
# Requests to /api/... go to the API app.
# All other requests go to the static file server.
app = DispatcherMiddleware(static_app, {
'/api': api_app,
})
return app
if __name__ == '__main__':
app = create_app()
print("Serving on http://localhost:5000... Press Ctrl+C to stop.")
run_simple('localhost', 5000, app, use_debugger=True, use_reloader=True)