Repository navigation
Refactor header exception logic into get_safe method
#779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -292,6 +292,16 @@ def copy(self) -> "Headers": | |
| copy._list = self._list.copy() | ||
| return copy | ||
|
|
||
| def get_safe(self, header: str) -> str: | ||
| from .exceptions import InvalidHeader | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I guess you've had to do this to avoid an import cycle. This is a very common issue since I implemented static type checking with mypy. The It's ugly but I'd rather have a module-level import at the bottom of a module than scattered imports inside functions. But if you're moving the code to websockets.handshake, the problem goes away. |
||
|
|
||
| try: | ||
| return self[header] | ||
| except KeyError as exc: | ||
| raise InvalidHeader(header) from exc | ||
| except MultipleValuesError as exc: | ||
| raise InvalidHeader(header, f"more than one {header} header found") from exc | ||
|
|
||
| # Collection methods | ||
|
|
||
| def __contains__(self, key: object) -> bool: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The only difference between
get_safeand__getitem__is thatget_safetranslatesKeyErrororMultipleValuesErrorintoInvalidHeader. Having two methods that do the same thing in the same class is weird.websockets.http.Headersis intended as a low-level utility that only knows about HTTP. This is why it useswebsockets.http.MultipleValuesErrorinstead of one of the websockets-specific exceptions inwebsockets.exceptions.To factor out this behavior, I'd write a utility function in
websockets.handshake. The job of this function would be to raise an exception fromwebsockets.exceptionsand to provide a good error message when the WebSocket protocol specifies that a given header must be provided exactly once, but it's there zero or multiple times.You can call it
get_unique_headerfor example.