Skip to content

Commit fdfd493

Browse files
Add _pipe_file and test to http (#1799)
--------- Co-authored-by: Martin Durant <[email protected]> Co-authored-by: Martin Durant <[email protected]>
1 parent ffdfed1 commit fdfd493

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

fsspec/implementations/http.py

+24
Original file line numberDiff line numberDiff line change
@@ -522,6 +522,30 @@ async def _isdir(self, path):
522522
except (FileNotFoundError, ValueError):
523523
return False
524524

525+
async def _pipe_file(self, path, value, mode="overwrite", **kwargs):
526+
"""
527+
Write bytes to a remote file over HTTP.
528+
529+
Parameters
530+
----------
531+
path : str
532+
Target URL where the data should be written
533+
value : bytes
534+
Data to be written
535+
mode : str
536+
How to write to the file - 'overwrite' or 'append'
537+
**kwargs : dict
538+
Additional parameters to pass to the HTTP request
539+
"""
540+
url = self._strip_protocol(path)
541+
headers = kwargs.pop("headers", {})
542+
headers["Content-Length"] = str(len(value))
543+
544+
session = await self.get_session()
545+
546+
async with session.put(url, data=value, headers=headers, **kwargs) as r:
547+
r.raise_for_status()
548+
525549

526550
class HTTPFile(AbstractBufferedFile):
527551
"""

fsspec/implementations/tests/test_http.py

+40
Original file line numberDiff line numberDiff line change
@@ -581,3 +581,43 @@ async def test_async_walk(server):
581581
pass
582582

583583
await fs._session.close()
584+
585+
586+
def test_pipe_file(server, tmpdir, reset_files):
587+
"""Test that the pipe_file method works correctly."""
588+
import io
589+
590+
import fsspec
591+
592+
# Create test data
593+
test_content = b"This is test data to pipe to a file"
594+
595+
# Initialize filesystem
596+
fs = fsspec.filesystem("http", headers={"accept_put": "true"})
597+
598+
# Test that the file doesn't exist yet
599+
with pytest.raises(FileNotFoundError):
600+
fs.info(server.address + "/piped_file")
601+
602+
# Pipe data to the file
603+
fs.pipe_file(server.address + "/piped_file", test_content)
604+
605+
# Verify the file exists now
606+
assert fs.exists(server.address + "/piped_file")
607+
608+
# Verify content
609+
assert fs.cat(server.address + "/piped_file") == test_content
610+
611+
# Test with different modes and headers
612+
fs.pipe_file(
613+
server.address + "/piped_file2",
614+
test_content,
615+
mode="overwrite",
616+
headers={"Content-Type": "text/plain"},
617+
)
618+
assert fs.cat(server.address + "/piped_file2") == test_content
619+
620+
# Test with byte-like object
621+
bytesio = io.BytesIO(b"BytesIO content")
622+
fs.pipe_file(server.address + "/piped_bytes", bytesio.getvalue())
623+
assert fs.cat(server.address + "/piped_bytes") == b"BytesIO content"

0 commit comments

Comments
 (0)