首页 > 解决方案 > 在 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_serverresume_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>'

标签: pythonmultithreadingaiohttp

解决方案


推荐阅读