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.

medium

While the use of separators optimizes the payload size, the current implementation has a few issues regarding efficiency and correctness:

  1. HTTP Keep-Alive: By not sending a Content-Length header, the server cannot support persistent connections (Keep-Alive) with many clients, as the client doesn't know when the response body ends unless the connection is closed. This significantly impacts performance for multiple requests.
  2. Error Handling: Serializing the JSON after sending the 200 OK status and headers is risky. If serialization fails (e.g., due to a non-serializable object), the client will receive a successful status code but a truncated or empty body.
  3. UTF-8 Optimization: Since you are explicitly setting charset=utf-8, you can set ensure_ascii=False in json.dumps. This allows non-ASCII characters to be encoded directly as UTF-8 bytes instead of being escaped (e.g., \u00e9), which is more efficient and aligned with the PR's goal of ensuring robust UTF-8 handling.
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:
# Serialize first to calculate Content-Length and catch errors before sending headers
payload = json.dumps(data, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
except (TypeError, ValueError):
self.send_error(500, "JSON serialization failed")
return
self.send_response(200)
self.send_header('Content-Type', 'application/json; charset=utf-8')
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