]> git.madduck.net Git - etc/vim.git/blob - src/blackd/middlewares.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Bump furo from 2022.2.14.1 to 2022.3.4 in /docs (#2906)
[etc/vim.git] / src / blackd / middlewares.py
1 from typing import Iterable, Awaitable, Callable
2 from aiohttp.web_response import StreamResponse
3 from aiohttp.web_request import Request
4 from aiohttp.web_middlewares import middleware
5
6 Handler = Callable[[Request], Awaitable[StreamResponse]]
7 Middleware = Callable[[Request, Handler], Awaitable[StreamResponse]]
8
9
10 def cors(allow_headers: Iterable[str]) -> Middleware:
11     @middleware
12     async def impl(request: Request, handler: Handler) -> StreamResponse:
13         is_options = request.method == "OPTIONS"
14         is_preflight = is_options and "Access-Control-Request-Method" in request.headers
15         if is_preflight:
16             resp = StreamResponse()
17         else:
18             resp = await handler(request)
19
20         origin = request.headers.get("Origin")
21         if not origin:
22             return resp
23
24         resp.headers["Access-Control-Allow-Origin"] = "*"
25         resp.headers["Access-Control-Expose-Headers"] = "*"
26         if is_options:
27             resp.headers["Access-Control-Allow-Headers"] = ", ".join(allow_headers)
28             resp.headers["Access-Control-Allow-Methods"] = ", ".join(
29                 ("OPTIONS", "POST")
30             )
31
32         return resp
33
34     return impl  # type: ignore