Skip to content

Instantly share code, notes, and snippets.

@smertelny
Last active September 25, 2018 20:40
Show Gist options
  • Select an option

  • Save smertelny/bc156848a46a0feb45331087dcae9b88 to your computer and use it in GitHub Desktop.

Select an option

Save smertelny/bc156848a46a0feb45331087dcae9b88 to your computer and use it in GitHub Desktop.
Just testet aiohttp server with subscription with RethinkDB
<html>
<head></head>
<body>
<h1>Hello World</h1>
<ul id="test">
</ul>
<input type='text' id="input_node"/>
<button onClick="send_data()">Send data!</button>
<script src="{{ static('index.js') }}"></script>
</body>
var socket = new WebSocket("ws://localhost:8000/ws");
function send_data () {
el = document.getElementById('input_node');
socket.send(el.value);
el.value = "";
}
socket.onopen = function() {
console.log("Connected");
};
socket.onclose = function(event) {
if (event.wasClean) {
alert('Clear exit');
} else {
alert('error connection'); // например, "убит" процесс сервера
}
alert('Code: ' + event.code + ' Event: ' + event.reason);
};
socket.onmessage = function(event) {
ul = document.getElementById("test");
li = document.createElement("li");
li.innerText = event.data;
ul.appendChild(li);
};
socket.onerror = function(error) {
alert("Error " + error.message);
};
import asyncio
import rethinkdb as r
import aiohttp
from aiohttp import web
import aiohttp_jinja2
import jinja2
r.set_loop_type('asyncio')
async def conn_pool():
return await r.connect(port=32772) # Change port on your own
async def sub(ws):
conn = await conn_pool()
try:
res = await r.table('tv_shows').changes().run(conn)
print("Waiting for news!")
while await res.fetch_next():
item = await res.next()
await ws.send_str(str(item))
except r.ReqlOpFailedError:
await ws.send_str("Could not connect to DB")
conn.close()
finally:
conn.close()
async def index(request):
ws = web.WebSocketResponse()
await ws.prepare(request)
await ws.send_str("Hello!")
asyncio.ensure_future(sub(ws))
async for msg in ws:
print("MESSAGE!!!!")
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close':
await ws.close()
else:
await ws.send_str(f"Message echo: {msg.data}")
print('Closing!')
return ws
@aiohttp_jinja2.template('index.j2')
async def main(request):
return {}
app = web.Application()
aiohttp_jinja2.setup(
app,
loader=jinja2.FileSystemLoader('./templates'),
auto_reload=True
)
app['static_root_url'] = "/static"
app.add_routes([
web.get('/', main),
web.get('/ws', index),
web.static('/static', './static')
])
# web.run_app(app, host="localhost", port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment