Search code examples
pythonstarlettehttpx

Merge dict header to request.headers.raw


headers.raw is typing.List[typing.Tuple[bytes, bytes]]

I want to merge it into another dict, like the one below:

client.build_request(headers=dict(request.headers.raw) | {"foo": "bar"}),

However I got the error

expected "Union[Headers, Dict[str, str], Dict[bytes, bytes], Sequence[Tuple[str, str]], Sequence[Tuple[bytes, bytes]], None]"

Is there some way to do this? I am using Python 3.10, and I was planning to use the new features on merging dicts


Solution

  • This is because your dict(request.headers.raw) is of type Dict[bytes, bytes] and {"foo": "bar"} is of type Dict[str, str]. So when you do dict(request.headers.raw) | {"foo": "bar"} it's of type Dict[bytes|str, bytes|str] which won't match with the expected headers type hence the error.

    So you could do this instead,

    client.build_request(headers=dict(request.headers.raw) | {b"foo": b"bar"})