Changeset View
Changeset View
Standalone View
Standalone View
swh/graph/server/app.py
Show First 20 Lines • Show All 168 Lines • ▼ Show 20 Lines | async def response_streamer(self, *args, **kwargs): | ||||
response.content_type = self.content_type | response.content_type = self.content_type | ||||
await response.prepare(self.request) | await response.prepare(self.request) | ||||
yield response | yield response | ||||
await response.write_eof() | await response.write_eof() | ||||
async def get(self): | async def get(self): | ||||
await self.prepare_response() | await self.prepare_response() | ||||
async with self.response_streamer() as self.response_stream: | async with self.response_streamer() as self.response_stream: | ||||
self._buf = [] | |||||
try: | |||||
await self.stream_response() | await self.stream_response() | ||||
finally: | |||||
await self._flush_buffer() | |||||
return self.response_stream | return self.response_stream | ||||
async def prepare_response(self): | async def prepare_response(self): | ||||
"""This can be overridden with some setup to be run before the response | """This can be overridden with some setup to be run before the response | ||||
actually starts streaming. | actually starts streaming. | ||||
""" | """ | ||||
pass | pass | ||||
async def stream_response(self): | async def stream_response(self): | ||||
"""Override this to perform the response streaming. Implementations of | """Override this to perform the response streaming. Implementations of | ||||
this should await self.stream_line(line) to write each line. | this should await self.stream_line(line) to write each line. | ||||
""" | """ | ||||
raise NotImplementedError | raise NotImplementedError | ||||
async def stream_line(self, line): | async def stream_line(self, line): | ||||
"""Write a line in the response stream.""" | """Write a line in the response stream.""" | ||||
await self.response_stream.write((line + "\n").encode()) | self._buf.append(line) | ||||
if len(self._buf) > 100: | |||||
await self._flush_buffer() | |||||
async def _flush_buffer(self): | |||||
await self.response_stream.write("\n".join(self._buf).encode() + b"\n") | |||||
self._buf = [] | |||||
class StatsView(GraphView): | class StatsView(GraphView): | ||||
"""View showing some statistics on the graph""" | """View showing some statistics on the graph""" | ||||
async def get(self): | async def get(self): | ||||
stats = self.backend.stats() | stats = self.backend.stats() | ||||
return aiohttp.web.Response(body=stats, content_type="application/json") | return aiohttp.web.Response(body=stats, content_type="application/json") | ||||
▲ Show 20 Lines • Show All 190 Lines • Show Last 20 Lines |