我开始做异步代码,但我仍然不完全理解它 .
我编写了一个程序来设置CherryPy Web服务器,并故意延迟返回GET请求 .
然后我使用aiohttp模块发出异步请求 .
What I did manage to do: 等待响应时运行一些打印循环
What I WANT to do effectively: 使循环运行,直到我得到响应(现在它继续运行)
那是我的代码:
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))
那么,如何使异步函数“相互”识别?
1 回答
使用变量,例如全局变量: