|
| 1 | +# Copyright 2019-2024 The University of Manchester, UK |
| 2 | +# Copyright 2020-2024 Vlaams Instituut voor Biotechnologie (VIB), BE |
| 3 | +# Copyright 2020-2024 Barcelona Supercomputing Center (BSC), ES |
| 4 | +# Copyright 2020-2024 Center for Advanced Studies, Research and Development in Sardinia (CRS4), IT |
| 5 | +# Copyright 2022-2024 École Polytechnique Fédérale de Lausanne, CH |
| 6 | +# Copyright 2024 Data Centre, SciLifeLab, SE |
| 7 | +# Copyright 2024 National Institute of Informatics (NII), JP |
| 8 | +# Copyright 2025 Senckenberg Society for Nature Research (SGN), DE |
| 9 | +# |
| 10 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 11 | +# you may not use this file except in compliance with the License. |
| 12 | +# You may obtain a copy of the License at |
| 13 | +# |
| 14 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | +# |
| 16 | +# Unless required by applicable law or agreed to in writing, software |
| 17 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 18 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 19 | +# See the License for the specific language governing permissions and |
| 20 | +# limitations under the License. |
| 21 | + |
| 22 | +""" |
| 23 | +Streaming RO-Crates from a web server |
| 24 | +
|
| 25 | +This example demonstrates how to create an RO-Crate on-the-fly |
| 26 | +and stream the result to the client. |
| 27 | +By using `stream_zip`, the RO-Crate is not written to disk and remote |
| 28 | +data is only fetched on the fly. |
| 29 | +
|
| 30 | +To run: `fastapi dev main.py`, then visit http://localhost:8000/crate |
| 31 | +""" |
| 32 | + |
| 33 | +from fastapi import FastAPI |
| 34 | +from fastapi.responses import StreamingResponse |
| 35 | +from rocrate.rocrate import ROCrate |
| 36 | +from io import StringIO |
| 37 | + |
| 38 | +app = FastAPI() |
| 39 | + |
| 40 | + |
| 41 | +@app.get("/crate") |
| 42 | +async def get(): |
| 43 | + crate = ROCrate() |
| 44 | + |
| 45 | + # Add a remote file |
| 46 | + crate.add_file( |
| 47 | + "https://raw.githubusercontent.com/ResearchObject/ro-crate-py/refs/heads/master/test/test-data/sample_file.txt", |
| 48 | + fetch_remote=True |
| 49 | + ) |
| 50 | + |
| 51 | + # Add a file containing a string to the crate |
| 52 | + crate.add_file( |
| 53 | + source=StringIO("Hello, World!"), |
| 54 | + dest_path="test-data/hello.txt" |
| 55 | + ) |
| 56 | + |
| 57 | + # Stream crate to client as a zip file |
| 58 | + return StreamingResponse( |
| 59 | + crate.stream_zip(), |
| 60 | + media_type="application/rocrate+zip", |
| 61 | + headers={ |
| 62 | + "Content-Disposition": "attachment; filename=crate.zip", |
| 63 | + } |
| 64 | + ) |
0 commit comments