Skip to content

Instantly share code, notes, and snippets.

@hqhs
Last active March 16, 2020 06:20
Show Gist options
  • Save hqhs/11da866a0cbdfc495f58a649a2986624 to your computer and use it in GitHub Desktop.
Save hqhs/11da866a0cbdfc495f58a649a2986624 to your computer and use it in GitHub Desktop.

попробовать можно так:

import aiohttp
import asyncio
import sys
from aiohttp import web
from aiojobs.aiohttp import setup, spawn

async def handle(request):
 response = web.StreamResponse()
 response.enable_chunked_encoding() # <---
 # ...
 code = 'import datetime;list(map(lambda x: print(datetime.datetime.now()), [x for x in range(10)]))'
 proc = await asyncio.create_subprocess_exec(sys.executable, '-c', code, stdout=asyncio.subprocess.PIPE)

 await response.prepare(request)

 while True:
  chunk = await proc.stdout.readline()

  if not chunk:
    break

  await asyncio.sleep(1)
  await response.write(chunk)

app = web.Application()
setup(app)
app.router.add_get('/', handle)
web.run_app(app)

потом запускаешь сервер и в другом окне:

nc 0.0.0.0 8080

пишешь ручками

GET / HTTP/1.1
Host: localhost
Connection: close

и два раза enter вывод:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: application/octet-stream
Date: Mon, 16 Mar 2020 06:12:54 GMT
Server: Python/3.7 aiohttp/3.6.2
Connection: close

1b
2020-03-16 09:12:54.554580

1b
2020-03-16 09:12:54.554599

1b
2020-03-16 09:12:54.554602
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment