Skip to main content
 首页 » 编程设计

python之使用 asyncio 及时更新一些数据并通过 aiohttp 呈现

2025年04月02日9exmyth

我正在尝试编写一个片段来研究 Python asyncio。基本思想是:

  1. 使用“简单的”网络服务器 (aiohttp) 向用户呈现一些数据

  2. 返回给用户的数据会及时变化

代码如下:

import asyncio 
import random 
from aiohttp import web 
 
userfeed = [] # the data suppose to return to the user via web browsers  
 
async def data_updater():  #to simulate data change promptly 
    while True: 
        await asyncio.sleep(3) 
        userfeed = [x for x in range(random.randint(1, 20))] 
        print('user date updated: ', userfeed) 
 
 
async def web_handle(request): 
    text = str(userfeed) 
    #print('in handler:', text)  # why text is empty? 
    return web.Response(text=text) 
 
async def init(loop): 
    app = web.Application(loop=loop) 
    app.router.add_route('GET', '/', web_handle) 
    srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000) 
    print('Server started @ http://127.0.0.1:8000...') 
    return srv 
 
loop = asyncio.get_event_loop() 
asyncio.ensure_future(data_updater())   
asyncio.ensure_future(init(loop)) 
loop.run_forever() 

问题是,代码正在运行(python 3.5),但 userfeed 在浏览器和 web_handler() 中始终为空 :-(

  1. 为什么 userfeed 没有更新?
  2. 关于这个timely date update函数,因为后面的更新机制可能比较复杂,比如可能涉及到async IO wait,有没有更好的方法代替while True: await asyncio .sleep(3) in data_updater() 以获得“更精确”的计时器?

请您参考如下方法:

主要问题是你忘记了语句 global userfeed在两个data_updater和 web_handle功能。所以,根据 how python resolves scopes , 在 web_handle它指的是您在 data_updater 中定义的全局变量到一个本地的,由语句 userfeed = [x for x ... 创建.在此上下文中使用全局变量是明确的 discouraged所以有一个使用 dict 的例子aiohttp.web.Application 的界面对象以在函数之间安全地引用您的变量。

import asyncio 
import random 
from aiohttp import web 
 
 
async def data_updater(app): 
    while True: 
        await asyncio.sleep(3) 
        app["userfeed"] = [x for x in range(random.randint(1, 20))] 
 
async def web_handle(request): 
    userfeed = request.app["userfeed"] 
    return web.Response(text=str(userfeed)) 
 
async def init(loop, port=8000): 
    app = web.Application(loop=loop) 
    app.router.add_route('GET', '/', web_handle) 
    handler = app.make_handler() 
    srv = await loop.create_server( 
        handler, '127.0.0.1', port=port) 
    return srv, app, handler 
 
if __name__ == "__main__": 
    loop = asyncio.get_event_loop() 
    srv, app, handler = loop.run_until_complete(init(loop, 8000)) 
    app['userfeed'] = [] 
    asyncio.ensure_future(data_updater(app)) 
    try: 
        loop.run_forever() 
    except KeyboardInterrupt: 
        pass 
    finally: 
        srv.close() 
        loop.run_until_complete(srv.wait_closed()) 
        loop.run_until_complete(app.shutdown()) 
        loop.run_until_complete(handler.finish_connections(60.0)) 
        loop.run_until_complete(app.cleanup()) 
    loop.close() 

当您在 127.0.0.1:8000 上刷新页面时您应该有一些新的随机数,因为它们每 3 秒在服务器端更新一次(您可以将 print 语句放回到 data_updater 中以验证它)。