Skip to content

Instantly share code, notes, and snippets.

@mivade
Last active May 4, 2023 16:51
Show Gist options
  • Save mivade/da3c80929cb8c9621bd6 to your computer and use it in GitHub Desktop.
Save mivade/da3c80929cb8c9621bd6 to your computer and use it in GitHub Desktop.
Websockets with Flask via aiohttp
"""Simple demo of using Flask with aiohttp via aiohttp-wsgi's
WSGIHandler.
"""
import asyncio
from aiohttp import web
from aiohttp_wsgi import WSGIHandler
from flask import Flask, render_template
app = Flask('aioflask')
app.config['DEBUG'] = True
app.jinja_loader.searchpath.insert(0, '.')
def counter():
num = 0
while True:
yield num
num += 1
@app.route('/')
def index():
return render_template('index.html')
async def socket(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
for x in counter():
try:
ws.send_str(str(x))
except:
pass
await asyncio.sleep(1)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
aio_app = web.Application()
wsgi = WSGIHandler(app)
aio_app.router.add_route('*', '/{path_info: *}', wsgi.handle_request)
aio_app.router.add_route('GET', '/socket', socket)
web.run_app(aio_app, port=5555)
<!doctype html>
<html>
<head>
<title>aioflask</title>
<script>
var ws = new WebSocket('ws://127.0.0.1:5555/socket');
ws.onmessage = function (msg) {
document.querySelector('#container').innerHTML = msg.data;
}
</script>
</head>
<body>
<div>
Seconds since websocket connected:
<span id="container"></span>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment