api.py
 1  import logging
 2  import os
 3  from socketserver import ThreadingMixIn
 4  from wsgiref.simple_server import make_server, WSGIServer
 5  import traceback
 6  import json
 7  import falcon
 8  
 9  from cors import set_cors
10  from static import StaticResource
11  
12  ###IMPORTS###
13  #from hellodb import HelloDBResource (just an example, not implemented)
14  #from hellodb import HelloDBSchemaResource (just an example, not implemented)
15  
16  cors = set_cors()
17  
18  def debug_error_serializer(req, resp, exception):
19      resp.content_type = falcon.MEDIA_JSON
20      # Format traceback directly from the exception if possible
21      tb = getattr(exception, '__traceback__', None)
22      if tb:
23          tb_str = ''.join(traceback.format_exception(type(exception), exception, tb))
24      else:
25          tb_str = 'Traceback unavailable'
26  
27      resp.text = json.dumps({
28          'title': str(exception),
29          'description': getattr(exception, 'description', None),
30          'traceback': tb_str
31      })
32  
33  LOGLEVEL = os.environ.get("LOGLEVEL", "DEBUG").upper()
34  logging.basicConfig(level=LOGLEVEL)
35  logger = logging.getLogger(__name__)
36  app = falcon.App(middleware=[cors.middleware])
37  
38  app.set_error_serializer(debug_error_serializer)
39  
40  # Instantiate StaticResource with the static directory
41  if os.environ.get("STATIC_DIR") != "-":
42      static_resource = StaticResource(os.environ.get("STATIC_DIR")   )
43      # Route handling:
44      app.add_route("/{filepath:path}", static_resource)
45      app.add_route("/", static_resource)
46  
47  ###ENDPOINTS###
48  #app.add_route("/hello_db", HelloDBResource()) (just an example, not implemented)
49  #app.add_route/"hello_db/schema", HelloDBSchemaResource()) (just an example, not implemented)
50  
51  class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
52      pass
53  
54  if __name__ == "__main__":
55      port = os.environ.get("PORT", "48000")
56      with make_server("", int(port), app, ThreadingWSGIServer) as httpd:
57          logger.info(f"Serving on port {port}...")
58  
59          httpd.serve_forever()