Search code examples
jsonpython-3.xflaskcurlcontainers

CURL response for python flask is different from LOCAL and Container


I have the below python (version 3.9) code with flask:

def get_location_by_ip(ip):
    url = f'{GEO_IP_SERVICE}/{ip}'

    response = requests.get(url)

    response.raise_for_status()

    return response.json()


@app.route('/v1/api/checkCurrentWeather')
def check_current_weather():
    try:
        location = get_location_by_ip(IP)
        city = location['city']
        country_code = location['countryCode']
    except Exception as ex:
        return {'message': 'FAILURE', 'ex': ex}, 500

    return {"city": city, "country": country_code}, 200

when I'm testing it locally using postman, it works well, and I'm getting the correct response, but when I'm testing it on container (on top of aws ubuntu instance with docker), I start to get this exception:

TypeError: Object of type HTTPError is not JSON serializable

I don't understand why the behavior is different. any idea?


Solution

  • Got the answer in the python chat room :) When doing:

    except Exception as ex:
        return {'message': 'FAILURE', 'ex': str(ex)}, 500
    

    str(ex) returns the real error:

    {
      "ex": "401 Client Error: Unauthorized for url: http://api.openweathermap.org/data/2.5/weather?q=Peta%E1%BA%96%20Tiqwa&appid=None",
      "message": "FAILURE"
    }
    

    ex is giving the exception object as JSON does not parse Exception object.

    Indeed, I forget to pass in my docker run command my env variable. After I did it, the response was as expected.

    Tnx to @12944qwerty for his suggestion.