1+ from __future__ import annotations
2+
13import json
24import sys
35import warnings
4- from io import BufferedIOBase
6+ from io import BytesIO
57from json .decoder import JSONDecodeError
6- from typing import Any , List , Optional , Tuple , Union
8+ from os import PathLike
9+ from typing import IO , Any , List , Optional , Tuple , Union
710
811import aiohttp
912import requests
1215from requests import Response
1316from requests .auth import HTTPBasicAuth
1417
18+ from databento .common .dbnstore import DBNStore
1519from databento .common .error import BentoClientError
1620from databento .common .error import BentoDeprecationWarning
1721from databento .common .error import BentoServerError
@@ -108,8 +112,8 @@ def _stream(
108112 url : str ,
109113 params : List [Tuple [str , Optional [str ]]],
110114 basic_auth : bool ,
111- writer : BufferedIOBase ,
112- ) -> None :
115+ path : Optional [ Union [ PathLike [ str ], str ]] = None ,
116+ ) -> DBNStore :
113117 self ._check_api_key ()
114118
115119 with requests .get (
@@ -123,16 +127,28 @@ def _stream(
123127 check_backend_warnings (response )
124128 check_http_error (response )
125129
130+ if path is None :
131+ writer : IO [bytes ] = BytesIO ()
132+ else :
133+ writer = open (path , "x+b" )
134+
126135 for chunk in response .iter_content (chunk_size = _32KB ):
127136 writer .write (chunk )
128137
138+ if path is None :
139+ writer .seek (0 )
140+ return DBNStore .from_bytes (writer )
141+
142+ writer .close ()
143+ return DBNStore .from_file (path )
144+
129145 async def _stream_async (
130146 self ,
131147 url : str ,
132148 params : List [Tuple [str , Optional [str ]]],
133149 basic_auth : bool ,
134- writer : BufferedIOBase ,
135- ) -> None :
150+ path : Optional [ Union [ PathLike [ str ], str ]] = None ,
151+ ) -> DBNStore :
136152 self ._check_api_key ()
137153
138154 async with aiohttp .ClientSession () as session :
@@ -148,9 +164,21 @@ async def _stream_async(
148164 check_backend_warnings (response )
149165 await check_http_error_async (response )
150166
167+ if path is None :
168+ writer : IO [bytes ] = BytesIO ()
169+ else :
170+ writer = open (path , "x+b" )
171+
151172 async for chunk in response .content .iter_chunks ():
152173 writer .write (chunk [0 ])
153174
175+ if path is None :
176+ writer .seek (0 )
177+ return DBNStore .from_bytes (writer )
178+
179+ writer .close ()
180+ return DBNStore .from_file (path )
181+
154182
155183def is_400_series_error (status : int ) -> bool :
156184 return status // 100 == 4
0 commit comments