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

The current implementation sends the 200 OK status and headers before serializing the data. If json.dumps fails (e.g., due to a non-serializable object), the server will have already sent a success status but will then fail to provide a valid body, resulting in a malformed HTTP response. It is safer to serialize the data first to handle errors gracefully. This also enables the inclusion of a Content-Length header, which is important for HTTP performance (enabling keep-alive) and helps clients verify they have received the complete payload. Additionally, since you are explicitly using UTF-8, adding ensure_ascii=False to json.dumps avoids unnecessary escaping of non-ASCII characters, optimizing payload size and speed. Note: The charset=utf-8 parameter is technically not defined for application/json per RFC 8259, though it is generally harmless.

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 handle errors and calculate Content-Length
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('Access-Control-Allow-Origin', '*')
self.send_header('Content-Length', str(len(payload)))
self.end_headers()
self.wfile.write(payload)


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