-
Notifications
You must be signed in to change notification settings - Fork 32
Case insensitive HTTPHeaders, HTTPResponse context manager and some fixes #29
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
Merged
dhalbert
merged 22 commits into
adafruit:main
from
michalpokusa:httpheaders-and-some-fixes
Jan 2, 2023
Merged
Changes from 6 commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
aad7010
Added HTTPHeaders
michalpokusa f1878b3
Replacing dict with HTTPHeaders in other modules
michalpokusa d547c7f
Fixed and extended docstrings
michalpokusa d0d5b80
Changed order of Docs References and updated version
michalpokusa d3adfd8
Fixed wrong content length for multibyte characters
michalpokusa be20bb1
Black format changes
michalpokusa aeb95a2
Encoding body only once when constructing response bytes
michalpokusa c1d2f55
Merge remote-tracking branch 'origin/main' into test
michalpokusa 00d3247
Refactor for unifying the HTTPResponse API
michalpokusa 2ca4756
Changed HTTPResponse to use context managers
michalpokusa a12d4ab
Minor changes to docstrings
michalpokusa c222d09
Changed send_chunk_body to send_chunk for unification
michalpokusa 4b61d74
Fix: Missing chunk length in ending message due to .lstrip()
michalpokusa f0b61a7
Prevented from calling .send() multiple times and added deprecation e…
michalpokusa e2e396b
Updated existing and added more examples
michalpokusa 287c5e0
Updated README.rst
michalpokusa 21aa09e
Fixed CI for examples/
michalpokusa d14a13a
Fix: Content type not setting properly
michalpokusa c758e51
Changed root to root_path in docstrings
michalpokusa 140c0e1
Minor adjustments to examples
michalpokusa c609a82
Changed address to client_address to match CPython's http.server modu…
michalpokusa 5b0135a
Changed version in docs/conf.py from 1.1.0 to 1.0, similar to other l…
michalpokusa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
# SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries | ||
# | ||
# SPDX-License-Identifier: MIT | ||
""" | ||
`adafruit_httpserver.headers.HTTPHeaders` | ||
==================================================== | ||
* Author(s): Michał Pokusa | ||
""" | ||
|
||
try: | ||
from typing import Dict, Tuple | ||
except ImportError: | ||
pass | ||
|
||
|
||
class HTTPHeaders: | ||
""" | ||
A dict-like class for storing HTTP headers. | ||
|
||
Allows access to headers using **case insensitive** names. | ||
|
||
Does **not** implement all dict methods. | ||
|
||
Examples:: | ||
|
||
headers = HTTPHeaders({"Content-Type": "text/html", "Content-Length": "1024"}) | ||
|
||
len(headers) | ||
# 2 | ||
|
||
headers.setdefault("Access-Control-Allow-Origin", "*") | ||
headers["Access-Control-Allow-Origin"] | ||
# '*' | ||
|
||
headers["Content-Length"] | ||
# '1024' | ||
|
||
headers["content-type"] | ||
# 'text/html' | ||
|
||
"CONTENT-TYPE" in headers | ||
# True | ||
""" | ||
|
||
_storage: Dict[str, Tuple[str, str]] | ||
|
||
def __init__(self, headers: Dict[str, str] = None) -> None: | ||
|
||
headers = headers or {} | ||
|
||
self._storage = {key.lower(): [key, value] for key, value in headers.items()} | ||
|
||
def get(self, name: str, default: str = None): | ||
"""Returns the value for the given header name, or default if not found.""" | ||
return self._storage.get(name.lower(), [None, default])[1] | ||
|
||
def setdefault(self, name: str, default: str = None): | ||
"""Sets the value for the given header name if it does not exist.""" | ||
return self._storage.setdefault(name.lower(), [name, default])[1] | ||
|
||
def items(self): | ||
"""Returns a list of (name, value) tuples.""" | ||
return dict(self._storage.values()).items() | ||
|
||
def keys(self): | ||
"""Returns a list of header names.""" | ||
return dict(self._storage.values()).keys() | ||
|
||
def values(self): | ||
"""Returns a list of header values.""" | ||
return dict(self._storage.values()).values() | ||
|
||
def update(self, headers: Dict[str, str]): | ||
"""Updates the headers with the given dict.""" | ||
return self._storage.update( | ||
{key.lower(): [key, value] for key, value in headers.items()} | ||
) | ||
|
||
def copy(self): | ||
"""Returns a copy of the headers.""" | ||
return HTTPHeaders(dict(self._storage.values())) | ||
|
||
def __getitem__(self, name: str): | ||
return self._storage[name.lower()][1] | ||
|
||
def __setitem__(self, name: str, value: str): | ||
self._storage[name.lower()] = [name, value] | ||
|
||
def __delitem__(self, name: str): | ||
del self._storage[name.lower()] | ||
|
||
def __iter__(self): | ||
return iter(dict(self._storage.values())) | ||
|
||
def __len__(self): | ||
return len(self._storage) | ||
|
||
def __contains__(self, key: str): | ||
return key.lower() in self._storage.keys() | ||
|
||
def __repr__(self): | ||
return f"{self.__class__.__name__}({dict(self._storage.values())})" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.