python异步通信_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))

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值