reflectionhandler.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. # Copyright (c) 2011 Google Inc. All rights reserved.
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions are
  5. # met:
  6. #
  7. # * Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # * Redistributions in binary form must reproduce the above
  10. # copyright notice, this list of conditions and the following disclaimer
  11. # in the documentation and/or other materials provided with the
  12. # distribution.
  13. # * Neither the name of Google Inc. nor the names of its
  14. # contributors may be used to endorse or promote products derived from
  15. # this software without specific prior written permission.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. import BaseHTTPServer
  29. import cgi
  30. import codecs
  31. import datetime
  32. import fnmatch
  33. import json
  34. import mimetypes
  35. import os.path
  36. import shutil
  37. import threading
  38. import time
  39. import urlparse
  40. import wsgiref.handlers
  41. import BaseHTTPServer
  42. class ReflectionHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  43. STATIC_FILE_EXTENSIONS = ['.js', '.css', '.html']
  44. # Subclasses should override.
  45. STATIC_FILE_DIRECTORY = None
  46. # Setting this flag to True causes the server to send
  47. # Access-Control-Allow-Origin: *
  48. # with every response.
  49. allow_cross_origin_requests = False
  50. def do_GET(self):
  51. self._handle_request()
  52. def do_POST(self):
  53. self._handle_request()
  54. def do_HEAD(self):
  55. self._handle_request()
  56. def read_entity_body(self):
  57. length = int(self.headers.getheader('content-length'))
  58. return self.rfile.read(length)
  59. def _read_entity_body_as_json(self):
  60. return json.loads(self.read_entity_body())
  61. def _handle_request(self):
  62. if "?" in self.path:
  63. path, query_string = self.path.split("?", 1)
  64. self.query = cgi.parse_qs(query_string)
  65. else:
  66. path = self.path
  67. self.query = {}
  68. function_or_file_name = path[1:] or "index.html"
  69. _, extension = os.path.splitext(function_or_file_name)
  70. if extension in self.STATIC_FILE_EXTENSIONS:
  71. self._serve_static_file(function_or_file_name)
  72. return
  73. function_name = function_or_file_name.replace(".", "_")
  74. if not hasattr(self, function_name):
  75. self.send_error(404, "Unknown function %s" % function_name)
  76. return
  77. if function_name[0] == "_":
  78. self.send_error(401, "Not allowed to invoke private or protected methods")
  79. return
  80. function = getattr(self, function_name)
  81. function()
  82. def _serve_static_file(self, static_path):
  83. self._serve_file(os.path.join(self.STATIC_FILE_DIRECTORY, static_path))
  84. def quitquitquit(self):
  85. self._serve_text("Server quit.\n")
  86. # Shutdown has to happen on another thread from the server's thread,
  87. # otherwise there's a deadlock
  88. threading.Thread(target=lambda: self.server.shutdown()).start()
  89. def _send_access_control_header(self):
  90. if self.allow_cross_origin_requests:
  91. self.send_header('Access-Control-Allow-Origin', '*')
  92. def _serve_text(self, text):
  93. self.send_response(200)
  94. self._send_access_control_header()
  95. self.send_header("Content-type", "text/plain")
  96. self.end_headers()
  97. self.wfile.write(text)
  98. def _serve_json(self, json_object):
  99. self.send_response(200)
  100. self._send_access_control_header()
  101. self.send_header('Content-type', 'application/json')
  102. self.end_headers()
  103. json.dump(json_object, self.wfile)
  104. def _serve_file(self, file_path, cacheable_seconds=0, headers_only=False):
  105. if not os.path.exists(file_path):
  106. self.send_error(404, "File not found")
  107. return
  108. with codecs.open(file_path, "rb") as static_file:
  109. self.send_response(200)
  110. self._send_access_control_header()
  111. self.send_header("Content-Length", os.path.getsize(file_path))
  112. mime_type, encoding = mimetypes.guess_type(file_path)
  113. if mime_type:
  114. self.send_header("Content-type", mime_type)
  115. if cacheable_seconds:
  116. expires_time = (datetime.datetime.now() +
  117. datetime.timedelta(0, cacheable_seconds))
  118. expires_formatted = wsgiref.handlers.format_date_time(
  119. time.mktime(expires_time.timetuple()))
  120. self.send_header("Expires", expires_formatted)
  121. self.end_headers()
  122. if not headers_only:
  123. shutil.copyfileobj(static_file, self.wfile)