How handle exception that value == None is ok and it should be passed?

I get response as None and its ok, it is not error. But every time when I run program I get exception.

        response = None
        try:
            if ~self.session.is_active:
                self.session.rollback()

           data = self.session.query(Data)
                               .filter(GeocoderData.address == address)
                                .first()
           response = data.yandex['response']
           logger.info(f"response = {str(e)}")

       except (TypeError, ValueError) as e:
            self.db_session.rollback()
            self.error = messages["db_error"]
            logger.error(f"{str(e)}")

        return response

I try to make like this:

 if response or response == None:

in try block, bit it doesnt work

How I should handle case, that get response = None is ok, it is not exception?

Answer

You are getting KeyError: 'response', because there is no field named response in data.yandex. Instead of getting dictionary value by square brackets:

data.yandes['response']

use getter, with specified default value

data.yandes.get('response', None)

This way, if there is no field named ‘response’, it will return None. The next thing to do, if you want the None response to be ok, but everything else bad, do:

if response is not None:
    raise ValueError

This way, if your response return None, program goes normally, but if its anything else but None, an error is thrown, and your except clause is being run.