Write a single JSON value into writer. Value is written as encoded by encoder.encode().
(self, value, encoder=None)
| 266 | return body |
| 267 | |
| 268 | def write_json(self, value, encoder=None): |
| 269 | """Write a single JSON value into writer. |
| 270 | |
| 271 | Value is written as encoded by encoder.encode(). |
| 272 | """ |
| 273 | |
| 274 | if self._closed: |
| 275 | # Don't log this - it's a common pattern to write to a stream while |
| 276 | # anticipating EOFError from it in case it got closed concurrently. |
| 277 | raise NoMoreMessages(stream=self) |
| 278 | |
| 279 | encoder = encoder if encoder is not None else self.json_encoder_factory() |
| 280 | writer = self._writer |
| 281 | |
| 282 | # Format the value as a message, and try to log any failures using as much |
| 283 | # information as we already have at the point of the failure. For example, |
| 284 | # if it fails after it is serialized to JSON, log that JSON. |
| 285 | |
| 286 | try: |
| 287 | body = encoder.encode(value) |
| 288 | except Exception: # pragma: no cover |
| 289 | self._log_message("<--", repr(value), logger=log.reraise_exception) |
| 290 | body = body.encode("utf-8") |
| 291 | |
| 292 | header = f"Content-Length: {len(body)}\r\n\r\n".encode("ascii") |
| 293 | data = header + body |
| 294 | data_written = 0 |
| 295 | try: |
| 296 | while data_written < len(data): |
| 297 | written = writer.write(data[data_written:]) |
| 298 | if written is not None: |
| 299 | data_written += written |
| 300 | writer.flush() |
| 301 | except Exception as exc: # pragma: no cover |
| 302 | self._log_message("<--", value, logger=log.swallow_exception) |
| 303 | raise JsonIOError(stream=self, cause=exc) |
| 304 | |
| 305 | self._log_message("<--", value) |
| 306 | |
| 307 | def __repr__(self): |
| 308 | return f"{type(self).__name__}({self.name!r})" |