server.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """
  2. Copyright 2022 The Rook Authors. All rights reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. """
  13. #!/usr/bin/env python3
  14. """
  15. Very simple HTTP server in python for logging requests
  16. Usage::
  17. ./server.py [<port>]
  18. """
  19. from http.server import BaseHTTPRequestHandler, HTTPServer
  20. import logging
  21. class S(BaseHTTPRequestHandler):
  22. def _set_response(self):
  23. self.send_response(200)
  24. self.send_header("Content-type", "text/html")
  25. self.end_headers()
  26. def do_POST(self):
  27. content_length = int(
  28. self.headers["Content-Length"]
  29. ) # <--- Gets the size of data
  30. post_data = self.rfile.read(content_length) # <--- Gets the data itself
  31. logging.info("POST request\nBody:\n%s\n", post_data.decode("utf-8"))
  32. def run(server_class=HTTPServer, handler_class=S, port=8080):
  33. logging.basicConfig(level=logging.INFO)
  34. server_address = ("", port)
  35. httpd = server_class(server_address, handler_class)
  36. logging.info("Starting httpd...\n")
  37. try:
  38. httpd.serve_forever()
  39. except KeyboardInterrupt:
  40. pass
  41. httpd.server_close()
  42. logging.info("Stopping httpd...\n")
  43. if __name__ == "__main__":
  44. from sys import argv
  45. if len(argv) == 2:
  46. run(port=int(argv[1]))
  47. else:
  48. run()