knowledge_seeker
knowledge_seeker

Reputation: 937

Converting python requests to aiohttp and adding error handling to it

This code was my synchronous code using the Python requests library:


    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

If I get an error while making the connection I wait for a second and try again, but if all goes well, then I break out of the loop and return the respose.

However, when I try to do that with 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

my IDE gives me a red zigzag line and tells me the following:

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.

How can I convert the same logic that I had with requests into aiohttp code?

Upvotes: 0

Views: 881

Answers (1)

Booboo
Booboo

Reputation: 44203

I assume your indentation reflects the fact that you are reproducing a method within a class. Anyway, you need to further indent your 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

Upvotes: 1

Related Questions