Skip to content

Instantly share code, notes, and snippets.

@jepler
Created July 1, 2024 15:03
Show Gist options
  • Save jepler/c65856945a505b9239f62d3055179bcb to your computer and use it in GitHub Desktop.
Save jepler/c65856945a505b9239f62d3055179bcb to your computer and use it in GitHub Desktop.
class FileOrStream:
def __init__(self, location):
self._location = location
self._response = None
self._raw = None
def __enter__(self):
location = self._location
self.location = None
if location is None:
raise RuntimeError(
"Object has been deinitialized and can no longer be used. Create a new object."
)
if location.startswith("http:") or location.startswith("https:"):
self._response = response = requests.get(
self._location, headers={"connection": "close"}, stream=True
)
# raw property not available in adafruit_requests, so try "socket" property too
# https://github.com/adafruit/Adafruit_CircuitPython_Requests/issues/198
raw = getattr(response, "raw")
if raw is None:
raw = response.socket
self._raw = raw
else:
self._response = None
self._raw = raw = open(location, "rb")
return raw
def __exit__(self, exc_type, exc_value, traceback):
response = self._response
raw = self._raw
self._response = None
self._raw = None
if response is not None:
response.__exit__(exc_type, exc_value, traceback)
elif raw is not None:
raw.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment