简易聊天室:
1、入口main.py
import logging import jinja2 import aiohttp_jinja2
from aiohttp import web
from aiohttpdemo_chat.views import index async def init_app(): app = web.Application() app['websockets'] = {} app.on_shutdown.append(shutdown) aiohttp_jinja2.setup(
app, loader=jinja2.PackageLoader('aiohttpdemo_chat', 'templates')) app.router.add_get('/', index) return app async def shutdown(app):
for ws in app['websockets'].values():
await ws.close()
app['websockets'].clear() def main():
# logging.basicConfig(level=logging.INFO)
logging.basicConfig(level=logging.INFO,
format="%(asctime)s [%(filename)s:%(lineno)d] %(message)s", datefmt="%m/%d/%Y %H:%M:%S [%A]") app = init_app()
web.run_app(app) if __name__ == '__main__':
main()
2、业务views.py
import logging import aiohttp
import aiohttp_jinja2
from aiohttp import web
from faker import Faker log = logging.getLogger(__name__) def get_random_name():
fake = Faker()
return fake.name() async def index(request):
ws_current = web.WebSocketResponse()
ws_ready = ws_current.can_prepare(request)
if not ws_ready.ok:
return aiohttp_jinja2.render_template('index.html', request, {}) await ws_current.prepare(request) name = get_random_name()
log.info('%s joined.', name) await ws_current.send_json({'action': 'connect', 'name': name}) for ws in request.app['websockets'].values():
await ws.send_json({'action': 'join', 'name': name})
request.app['websockets'][name] = ws_current while True:
msg = await ws_current.receive()
logging.info(msg.type)
if msg.type == aiohttp.WSMsgType.text:
for ws in request.app['websockets'].values():
if ws is not ws_current:
await ws.send_json(
{'action': 'sent', 'name': name, 'text': msg.data})
else: break del request.app['websockets'][name]
log.info('%s disconnected.', name)
for ws in request.app['websockets'].values():
await ws.send_json({'action': 'disconnect', 'name': name}) return ws_current
展示:
引用-https://github.com/lianzhilei/aiohttp-demos/tree/master/demos/chat