我对asyncio和aiohttp以及WebSocket都是新手。基本上,我需要生成一个随机字符串,每秒更改一次,并在网页上显示其值,而无需刷新。
我编写了以下代码:
import asyncio
import random
import string
from aiohttp import web
async def index(request):
return web.Response(text=periodic())
@asyncio.coroutine
def periodic():
while True:
print(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)))
yield from asyncio.sleep(1)
def stop():
task.cancel()
task = asyncio.Task(periodic())
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
但它只在控制台中显示随机字符串值。
from aiohttp import web
from routes import setup_routes
app = web.Application()
setup_routes(app)
web.run_app(app, host='127.0.0.1', port=8080)
路线。py公司
from app import index
def setup_routes(app):
app.router.add_get('/', index)