Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions simple_seismic_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ def do_GET(self):

def send_json(self, data):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(data, separators=(',', ':')).encode())
self.wfile.write(json.dumps(data, separators=(',', ':')).encode('utf-8'))
Comment on lines 111 to +115

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

While the move to compact JSON is a good optimization, this implementation can be further improved for robustness, performance, and standards compliance:

  1. Robustness: Serializing the JSON before sending the 200 OK status allows the server to handle errors (e.g., if data contains non-serializable objects) gracefully by returning a 500 Internal Server Error. Currently, if json.dumps fails, the headers have already been sent, resulting in a malformed response.
  2. Performance: Adding a Content-Length header is a significant optimization for production APIs as it enables HTTP persistent connections (Keep-Alive), reducing latency for subsequent requests.
  3. Standards Compliance: The charset=utf-8 parameter is not defined for the application/json media type (RFC 8259). JSON is UTF-8 by default.
  4. Efficiency: Using ensure_ascii=False is slightly faster and produces smaller payloads when non-ASCII characters are present, as it avoids unnecessary escaping. Additionally, .encode() defaults to UTF-8 in Python 3, so the explicit argument is redundant.
Suggested change
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(json.dumps(data, separators=(',', ':')).encode())
self.wfile.write(json.dumps(data, separators=(',', ':')).encode('utf-8'))
try:
payload = json.dumps(data, separators=(',', ':'), ensure_ascii=False).encode()
except (TypeError, ValueError):
self.send_error(500, "Internal Server Error: JSON serialization failed")
return
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.send_header('Content-Length', str(len(payload)))
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(payload)


def log_message(self, format, *args):
"""Override to customize logging"""
Expand Down
Loading