python - 在 python+aiohttp 中,路由是多线程的吗?在代码运行时如何在路由之间进行通信?
问题描述
我有一个 python-aiohttp 网络服务。我想让路由以这种方式相互交互:
# http://base/pause
async def pause_server(self, request):
self._is_paused = True
return json_response(data={'paused': true})
# http://base/resume
async def resume_server(self, request):
self._is_paused = False
return json_response(data={'paused': false})
# http://base/getData
async def get_data(self, request):
while self._is_paused:
time.sleep(0.1)
return json_response(data=data)
我发现如果我调用pause_server
,然后在单独的选项卡调用get_data
中,服务器会按我的预期休眠,但是一旦我调用resume_server
,resume_server
代码就不会被调用,服务器会继续在get_data
代码中无限期地休眠。这是我可以用 python-aiohttp 做的吗?我猜想每条路由都在自己的线程上运行,但如果是这样的话,我希望这段代码可以工作。
我为什么要这样做?我正在对使用 aiohttp 托管 REST 服务的 python 应用程序进行一些行为测试。当我的页面正在加载时,我想在屏幕上显示一些“正在加载...”文本。当我现在编写行为测试时,它们看起来像这样:
Scenario: Load the page
Given the server takes 5 seconds to respone
And I go to the page
Then the data is 'Loading...'
Given I wait 5 seconds
Then the data is '<data>'
这依赖于服务器需要一定的时间来运行。如果我将服务器设置为等待太久,测试将永远运行。如果我将等待时间设置得太短,测试就会开始失败,因为实际运行它们需要一段时间。
我宁愿做这样的事情:
Scenario: Load the page
Given I pause the server # calls pause_server endpoint
And I go to the page # calls get_data endpoint
Then the data is 'Loading...'
Given I resume the server # calls resume_server endpoint
Then the data is '<data>'
解决方案
推荐阅读
- linux - 如何检查守护程序是否作为脚本的一部分成功启动?
- flutter - Flutter:从 Firebase 实时数据库项目创建 GridView
- reactjs - 调用浏览器上的后退按钮时未调用 Componentdidmount-ReactJS
- java - Java 文件 I/O 问题:文件现在由 newBufferedWriter 写入
- sql - 在开始行的结束日期和结束时间列添加结束日期和时间值
- python - 使用 Python 输出重复值 ID 和非重复值的列表
- laravel - Laravel:具有相同位置和名称的多条路线
- keras - 实现SRCNN时获取卷积算法失败
- list - 测试嵌套列表中的对角相邻元素
- angular - 使用 Angular cli 进行单元测试,http 测试不起作用