我开始做异步代码,但我还是不完全理解它。
我编写了一个设置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))
那么,我如何制作异步功能"意识到"彼此?
答案 0 :(得分:0)
使用变量,例如global ::
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!")