在python+aiohttp中,路由是多线程的吗?当路由的代码运行时,如何在路由之间进行通信?

2024-04-26 21:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python aiohttp web服务。我想让路线以这种方式相互作用:

# 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>'

Tags: theself服务器httpdatagetaiohttpserver