Python:如何使这些异步方法进行通信?

2024-10-01 11:27:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始做异步代码,但我仍然不完全理解它。在

我编写了一个程序来设置CherryPy web服务器,并故意延迟GET请求的返回。
然后我使用aiohttp模块发出一个异步请求。在

我做了些什么: 在等待响应的同时运行一些打印循环
我想有效地做什么: 让循环运行直到我得到响应(现在它只是继续运行)

这是我的准则:

import cherrypy
import time
import threading
import asyncio
import aiohttp


# The Web App
class CherryApp:
    @cherrypy.expose
    def index(self):
        time.sleep(5)
        return open('views/index.html')


async def get_page(url):
    session = aiohttp.ClientSession()
    resp = await session.get(url)
    return resp

async def waiter():

    # I want to break this loop when I get a response
    while True:
        print("Waiting for response")
        await asyncio.sleep(1)


if __name__ == '__main__':
    # Start the server
    server = threading.Thread(target=cherrypy.quickstart, args=[CherryApp()])
    server.start()

    # Run the async methods
    event_loop = asyncio.get_event_loop()
    tasks = [get_page('http://127.0.0.1:8080/'), waiter()]

    # Obviously, the 'waiter()' method never completes, so this just runs forever
    event_loop.run_until_complete(asyncio.wait(tasks))

那么,如何使异步函数相互“感知”?在


Tags: theimportloopeventasynciogetasyncaiohttp
1条回答
网友
1楼 · 发布于 2024-10-01 11:27:37

使用变量,例如全局变量:

done = False

async def get_page(url):
    global done
    session = aiohttp.ClientSession()
    resp = await session.get(url)
    done = True
    return resp

async def waiter():
    while not done:
        print("Waiting for response")
        await asyncio.sleep(1)
    print("done!")

相关问题 更多 >