poc.py 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import asyncio
  2. import aiohttp
  3. import json
  4. from aiohttp import web
  5. async def uptime_handler(request):
  6. resp = web.StreamResponse(
  7. status=200,
  8. reason='OK',
  9. headers={
  10. 'Content-Type': 'text/csv',
  11. 'Content-Disposition': 'attachment; filename="filename.csv"',
  12. }
  13. )
  14. await resp.prepare(request)
  15. try:
  16. async with aiohttp.ClientSession(loop=loop) as session:
  17. url = 'http://localhost:8086/query?chunk_size=1000&chunked=true&db=resourceAux&q=SELECT+%2A+FROM+resource_aux' # nopep8
  18. async with session.get(url) as response:
  19. async for chunk in response.content:
  20. bytes_to_str = chunk.decode('utf-8')
  21. result = json.loads(bytes_to_str)['results'][0]['series'][0]['values'] # nopep8
  22. for r in result:
  23. await resp.write(str.encode(str(r)+'\n'))
  24. except Exception as e:
  25. # So you can observe on disconnects and such.
  26. print(repr(e))
  27. raise
  28. return resp
  29. async def build_server(loop, address, port):
  30. app = web.Application(loop=loop)
  31. app.router.add_route('GET', "/uptime", uptime_handler)
  32. return await loop.create_server(app.make_handler(), address, port)
  33. if __name__ == '__main__':
  34. loop = asyncio.get_event_loop()
  35. loop.run_until_complete(build_server(loop, 'localhost', 9999))
  36. print("Server ready!")
  37. try:
  38. loop.run_forever()
  39. except KeyboardInterrupt:
  40. print("Shutting Down!")
  41. loop.close()