Requests-File
Requests-File is a transport adapter for the popular Python Requests library, enabling local filesystem access via `file://` URLs. It allows `requests.Session` objects to fetch local files as if they were remote resources. The current version is 3.0.1, and it follows the release cadence of its underlying dependency, `requests`, which is actively maintained and frequently updated.
Warnings
- gotcha When accessing `response.text`, the encoding is inferred by `chardet` (if installed) or defaults to `ISO-8859-1`. This might not always match the actual file encoding, potentially leading to incorrect decoding. For binary files or specific encodings, it's safer to use `response.content` and decode manually.
- gotcha requests-file maps common file system errors to HTTP status codes: `EACCES` (permission denied) is converted to a 403 Forbidden, `ENOENT` (file not found) to a 404 Not Found, and other `IOError` types to a 400 Bad Request. Be aware of these mappings when implementing error handling.
- gotcha As a `requests` transport adapter, `requests-file` relies on `requests`'s internal adapter API. Future major versions of the `requests` library might introduce breaking changes to this API (e.g., changes to `HTTPAdapter` or connection management), which could potentially affect `requests-file`'s functionality or require updates. For example, recent `requests` versions had changes related to `SSLContext` caching and the `_get_connection` method which could impact custom adapters.
Install
-
pip install requests-file
Imports
- FileAdapter
from requests_file import FileAdapter
Quickstart
import requests
from requests_file import FileAdapter
import os
# Create a dummy file for demonstration
file_content = "Hello from local file!"
file_path = "./test_file.txt"
with open(file_path, "w") as f:
f.write(file_content)
s = requests.Session()
s.mount('file://', FileAdapter())
# Construct a file:// URL (absolute path is recommended)
absolute_file_path = os.path.abspath(file_path)
file_url = f'file://{absolute_file_path}'
try:
response = s.get(file_url)
response.raise_for_status() # Raise an exception for HTTP errors
print(f"Status Code: {response.status_code}")
print(f"Content: {response.text}")
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
finally:
# Clean up the dummy file
os.remove(file_path)