将 python 请求转换为 aiohttp 并向其添加错误处理

Converting python requests to aiohttp and adding error handling to it

此代码是我使用 Python 请求库的同步代码:


    def request_with_error_handling(self, item_id):
        browse_url = f'https://api.ebay.com/buy/browse/v1/item/v1|{item_id}|0'
        while True:
            try:
                rq = requests.get(browse_url, headers=self.browse_headers)
                break
            except Exception as e:
                print(f'An error has occurred while processing the request: {str(e)}')
                t.sleep(1)

        return rq

如果我在建立连接时遇到错误,我会等待一秒钟然后重试,但如果一切顺利,那么我会跳出循环并 return 响应。

但是,当我尝试使用 aiohttp 执行此操作时:

    async def request_with_error_handling(self, browse_url):
        async with aiohttp.ClientSession() as session:
            while True:
                try:
                    async with session.get(browse_url, headers=self.browse_headers) as response:
                    break
                except Exception as e:
                    print(
                        f'An error has occurred while processing the request: {str(e)}')
                    t.sleep(1)

        return response

我的 IDE 给了我一条红色锯齿线并告诉我以下内容:

The break statement break_stmt ::= "break" break may only occur syntactically nested in a for or while loop, but not nested in a function or class definition within that loop. It terminates the nearest enclosing loop, skipping the optional else clause if the loop has one. If a for loop is terminated by break, the loop control target keeps its current value. When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

如何将请求中的相同逻辑转换为 aiohttp 代码?

我假设您的缩进反映了您正在 class 中复制方法这一事实。无论如何,您需要进一步缩进 break:

    async def request_with_error_handling(self, browse_url):
        async with aiohttp.ClientSession() as session:
            while True:
                try:
                    async with session.get(browse_url, headers=self.browse_headers) as response:
                        break
                except Exception as e:
                    print(
                        f'An error has occurred while processing the request: {str(e)}')
                    t.sleep(1)

        return response