Skip to content

Commit

Permalink
Switching to streaming response to avoid writing geneset file to disk
Browse files Browse the repository at this point in the history
  • Loading branch information
bergsalex committed Jul 15, 2024
1 parent 2c2e632 commit e47573d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 10 deletions.
21 changes: 12 additions & 9 deletions src/geneweaver/api/controller/genesets.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
"""Endpoints related to genesets."""

import json
import os
import time
from tempfile import TemporaryDirectory
from typing import Optional, Set

from fastapi import APIRouter, Depends, HTTPException, Path, Query, Security
from fastapi.responses import FileResponse
from fastapi.responses import FileResponse, StreamingResponse
from geneweaver.api import dependencies as deps
from geneweaver.api.schemas.apimodels import GeneValueReturn
from geneweaver.api.schemas.auth import UserInternal
Expand Down Expand Up @@ -189,7 +188,7 @@ def get_export_geneset_by_id_type(
cursor: Optional[deps.Cursor] = Depends(deps.cursor),
temp_dir: TemporaryDirectory = Depends(deps.get_temp_dir),
gene_id_type: Optional[GeneIdentifier] = None,
) -> FileResponse:
) -> StreamingResponse:
"""Export geneset into JSON file. Search by ID and optional gene identifier type."""
timestr = time.strftime("%Y%m%d-%H%M%S")

Expand All @@ -214,15 +213,19 @@ def get_export_geneset_by_id_type(
geneset_filename = f"geneset_{geneset_id}_{timestr}.json"

# Write the data to temp file
temp_file_path = os.path.join(temp_dir, geneset_filename)
with open(temp_file_path, "w") as f:
json.dump(response, f, default=str)
from io import StringIO

buffer = StringIO()

json.dump(response, buffer, default=str)

buffer.seek(0)

# Return as a download
return FileResponse(
path=temp_file_path,
return StreamingResponse(
buffer,
media_type="application/octet-stream",
filename=geneset_filename,
headers={"Content-Disposition": f"attachment; filename={geneset_filename}"},
)


Expand Down
1 change: 0 additions & 1 deletion tests/controllers/test_genesets.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ def test_export_geneset_w_gene_id_type(mock_service_get_geneset_w_gene_id_type,
response = client.get("/api/genesets/1234/file?gene_id_type=2")

assert response.headers.get("content-type") == "application/octet-stream"
assert int(response.headers.get("content-length")) > 0
assert response.status_code == 200


Expand Down

0 comments on commit e47573d

Please sign in to comment.