(
request: web.Request,
executor: Executor,
executor_semaphore: asyncio.BoundedSemaphore,
)
| 152 | |
| 153 | |
| 154 | async def handle( |
| 155 | request: web.Request, |
| 156 | executor: Executor, |
| 157 | executor_semaphore: asyncio.BoundedSemaphore, |
| 158 | ) -> web.Response: |
| 159 | headers = {BLACK_VERSION_HEADER: __version__} |
| 160 | try: |
| 161 | if request.headers.get(PROTOCOL_VERSION_HEADER, "1") != "1": |
| 162 | return web.Response( |
| 163 | status=501, text="This server only supports protocol version 1" |
| 164 | ) |
| 165 | |
| 166 | fast = False |
| 167 | if request.headers.get(FAST_OR_SAFE_HEADER, "safe") == "fast": |
| 168 | fast = True |
| 169 | try: |
| 170 | mode = parse_mode(request.headers) |
| 171 | except HeaderError as e: |
| 172 | return web.Response(status=400, text=e.args[0]) |
| 173 | req_bytes = await request.read() |
| 174 | charset = request.charset if request.charset is not None else "utf8" |
| 175 | req_str = req_bytes.decode(charset) |
| 176 | then = datetime.now(timezone.utc) |
| 177 | |
| 178 | header = "" |
| 179 | if mode.skip_source_first_line: |
| 180 | first_newline_position: int = req_str.find("\n") + 1 |
| 181 | header = req_str[:first_newline_position] |
| 182 | req_str = req_str[first_newline_position:] |
| 183 | |
| 184 | only_diff = bool(request.headers.get(DIFF_HEADER, False)) |
| 185 | formatted_str = await format_code( |
| 186 | req_str=req_str, |
| 187 | fast=fast, |
| 188 | mode=mode, |
| 189 | then=then, |
| 190 | only_diff=only_diff, |
| 191 | executor=executor, |
| 192 | executor_semaphore=executor_semaphore, |
| 193 | ) |
| 194 | |
| 195 | # Put the source first line back |
| 196 | req_str = header + req_str |
| 197 | formatted_str = header + formatted_str |
| 198 | |
| 199 | return web.Response( |
| 200 | content_type=request.content_type, |
| 201 | charset=charset, |
| 202 | headers=headers, |
| 203 | text=formatted_str, |
| 204 | ) |
| 205 | except black.NothingChanged: |
| 206 | return web.Response(status=204, headers=headers) |
| 207 | except black.InvalidInput as e: |
| 208 | return web.Response(status=400, headers=headers, text=str(e)) |
| 209 | except black.SourceASTParseError as e: |
| 210 | return web.Response(status=400, headers=headers, text=str(e)) |
| 211 | except web.HTTPException: |
no test coverage detected