mirror of
https://github.com/home-assistant/core.git
synced 2025-07-20 03:37:07 +00:00
Reduce overhead to run headers middleware (#142032)
Instead of having to itererate a dict, update the headers multidict using a pre-build CIMultiDict which has an internal fast path
This commit is contained in:
parent
2305cb0131
commit
bb7e1d4723
@ -3,25 +3,34 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from collections.abc import Awaitable, Callable
|
from collections.abc import Awaitable, Callable
|
||||||
|
from typing import Final
|
||||||
|
|
||||||
|
from aiohttp import hdrs
|
||||||
from aiohttp.web import Application, Request, StreamResponse, middleware
|
from aiohttp.web import Application, Request, StreamResponse, middleware
|
||||||
from aiohttp.web_exceptions import HTTPException
|
from aiohttp.web_exceptions import HTTPException
|
||||||
|
from multidict import CIMultiDict, istr
|
||||||
|
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
|
|
||||||
|
REFERRER_POLICY: Final[istr] = istr("Referrer-Policy")
|
||||||
|
X_CONTENT_TYPE_OPTIONS: Final[istr] = istr("X-Content-Type-Options")
|
||||||
|
X_FRAME_OPTIONS: Final[istr] = istr("X-Frame-Options")
|
||||||
|
|
||||||
|
|
||||||
@callback
|
@callback
|
||||||
def setup_headers(app: Application, use_x_frame_options: bool) -> None:
|
def setup_headers(app: Application, use_x_frame_options: bool) -> None:
|
||||||
"""Create headers middleware for the app."""
|
"""Create headers middleware for the app."""
|
||||||
|
|
||||||
added_headers = {
|
added_headers = CIMultiDict(
|
||||||
"Referrer-Policy": "no-referrer",
|
{
|
||||||
"X-Content-Type-Options": "nosniff",
|
REFERRER_POLICY: "no-referrer",
|
||||||
"Server": "", # Empty server header, to prevent aiohttp of setting one.
|
X_CONTENT_TYPE_OPTIONS: "nosniff",
|
||||||
|
hdrs.SERVER: "", # Empty server header, to prevent aiohttp of setting one.
|
||||||
}
|
}
|
||||||
|
)
|
||||||
|
|
||||||
if use_x_frame_options:
|
if use_x_frame_options:
|
||||||
added_headers["X-Frame-Options"] = "SAMEORIGIN"
|
added_headers[X_FRAME_OPTIONS] = "SAMEORIGIN"
|
||||||
|
|
||||||
@middleware
|
@middleware
|
||||||
async def headers_middleware(
|
async def headers_middleware(
|
||||||
|
Loading…
x
Reference in New Issue
Block a user