[英]Python: how do I make these asynchronous methods communicate?
我开始做异步代码,但我仍然不完全了解它。
我编写了一个程序,该程序设置了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))
那么,如何使异步函数彼此“感知”呢?
使用变量,例如,全局变量:
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!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.