|
45 | 45 |
|
46 | 46 | HAR_VERSION = "1.2" |
47 | 47 |
|
| 48 | +# A single reusable encoder avoids the per-call argument handling in ``json.dumps``. |
| 49 | +# With default options this produces output identical to ``json.dumps(obj)``. |
| 50 | +_encode = json.JSONEncoder().encode |
| 51 | + |
48 | 52 |
|
49 | 53 | class HarFile: |
50 | 54 | _fd: IO[str] |
@@ -140,25 +144,27 @@ def add_entry( |
140 | 144 | self._has_preable = True |
141 | 145 | separator = "\n" if self._is_first_entry else ",\n" |
142 | 146 | self._is_first_entry = False |
143 | | - write = self._fd.write |
144 | | - dumps = json.dumps |
| 147 | + dumps = _encode |
145 | 148 | if isinstance(startedDateTime, datetime): |
146 | 149 | startedDateTime = startedDateTime.isoformat() |
147 | | - write(f"{separator} {{") |
148 | | - write(f'\n "startedDateTime": "{startedDateTime}",') |
149 | | - write(f'\n "time": {time},') |
150 | | - write(f'\n "request": {dumps(request.asdict())},') |
151 | | - write(f'\n "response": {dumps(response.asdict())},') |
152 | | - write(f'\n "timings": {dumps(timings.asdict())},') |
153 | 150 | cache = cache or Cache() |
154 | | - write(f'\n "cache": {dumps(cache.asdict())}') |
| 151 | + chunk = ( |
| 152 | + f"{separator} {{" |
| 153 | + f'\n "startedDateTime": "{startedDateTime}",' |
| 154 | + f'\n "time": {time},' |
| 155 | + f'\n "request": {dumps(request.asdict())},' |
| 156 | + f'\n "response": {dumps(response.asdict())},' |
| 157 | + f'\n "timings": {dumps(timings.asdict())},' |
| 158 | + f'\n "cache": {dumps(cache.asdict())}' |
| 159 | + ) |
155 | 160 | if serverIPAddress: |
156 | | - write(f',\n "serverIPAddress": {dumps(serverIPAddress)}') |
| 161 | + chunk += f',\n "serverIPAddress": {dumps(serverIPAddress)}' |
157 | 162 | if connection: |
158 | | - write(f',\n "connection": {dumps(connection)}') |
| 163 | + chunk += f',\n "connection": {dumps(connection)}' |
159 | 164 | if comment: |
160 | | - write(f',\n "comment": {dumps(comment)}') |
161 | | - write("\n }") |
| 165 | + chunk += f',\n "comment": {dumps(comment)}' |
| 166 | + chunk += "\n }" |
| 167 | + self._fd.write(chunk) |
162 | 168 |
|
163 | 169 | def _write_preamble(self) -> None: |
164 | 170 | creator = f"""{{ |
|
0 commit comments