From 1a4253f1432ec92a0951a99e43afc0da16722fb7 Mon Sep 17 00:00:00 2001 From: Daniel Bauer Date: Mon, 27 Jan 2025 12:39:03 +0100 Subject: [PATCH] feat: add streaming example --- examples/fastapi/main.py | 45 +++++++++++++++++++++++++++++++ examples/fastapi/requirements.txt | 3 +++ 2 files changed, 48 insertions(+) create mode 100644 examples/fastapi/main.py create mode 100644 examples/fastapi/requirements.txt diff --git a/examples/fastapi/main.py b/examples/fastapi/main.py new file mode 100644 index 00000000..6c5acf0e --- /dev/null +++ b/examples/fastapi/main.py @@ -0,0 +1,45 @@ +""" +Streaming RO-Crates from a web server + +This example demonstrates how to create an RO-Crate on-the-fly +and stream the result to the client. +By using `stream_zip`, the RO-Crate is not written to disk and remote +data is only fetched on the fly. + +To run: `fastapi dev main.py`, then visit http://localhost:8000/crate +""" + +from fastapi import FastAPI +from fastapi.responses import StreamingResponse +from rocrate.rocrate import ROCrate +from io import StringIO + +app = FastAPI() + +@app.get("/crate") +async def get(): + crate = ROCrate() + + # Add a remote file + crate.add_file( + "https://raw.githubusercontent.com/ResearchObject/ro-crate-py/refs/heads/master/test/test-data/sample_file.txt", + fetch_remote=True + ) + + # Add a file containing a string to the crate + crate.add_file( + source=StringIO("Hello, World!"), + dest_path="test-data/hello.txt" + ) + + # Stream crate to client as a zip file + return StreamingResponse( + crate.stream_zip(), + media_type="application/rocrate+zip", + headers={ + "Content-Disposition": "attachment; filename=crate.zip", + } + ) + + + diff --git a/examples/fastapi/requirements.txt b/examples/fastapi/requirements.txt new file mode 100644 index 00000000..09eae111 --- /dev/null +++ b/examples/fastapi/requirements.txt @@ -0,0 +1,3 @@ +../../ +fastapi +fastapi-cli