[Python] Response object is not subscriptable

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    @app.route('/twoHourForecast')
    def get_twoHourForecast():
    twoHourDataUrl = "https://api.data.gov.sg/v1/environment/2-hour-weather-forecast" # Corrected URL

    #Create 2 lists for each value in the JSON file from the API
    twoHourData_Area = []
    twoHourData_Forecast = []
    response = requests.get(twoHourDataUrl)

    if response.status_code != 200:
    print("Error fetching weather data:", response.status_code)
    return []

    # Parse the response as JSON
    twoHourData = response.json()

    # Check if the required keys exist in the JSON data
    if "items" in twoHourData and len(twoHourData["items"]) > 0:
    forecast_data = twoHourData["items"][0]["forecasts"] # Access the forecast data

    for entry in forecast_data:
    area = entry['area'] # Get the area
    forecast = entry['forecast'] # Get the forecast

    # Append to respective lists
    twoHourData_Area.append({'area': area})
    twoHourData_Forecast.append({'forecast': forecast})

    # To check if there is any data through the terminal
    print(f"Area: {twoHourData_Area}, Forecast: {twoHourData_Forecast}")

    # TODO: Add data for each type of forecast data
    Fair = 0
    Fair_Day = 1
    Fair_Night = 2
    Fair_and_Warm = 3
    Partly_Cloudy = 4
    Partly_Cloudy_Day = 5
    Partly_Cloudy_Night = 6
    Cloudy = 7
    Hazy = 8
    Slightly_Hazy = 9
    Windy = 10
    Mist = 11
    Fog = 12
    Light_Rain = 13
    Moderate_Rain = 14
    Heavy_Rain = 15
    Passing_Showers = 16
    Light_Showers = 17
    Showers = 19
    Heavy_Showers = 20
    Thundery_Showers = 21
    Heavy_Thundery_Showers = 22
    Heavy_Thundery_Showers_with_Gusty_Winds =23

    # Return both lists
    return jsonify(twoHourData_Area, twoHourData_Forecast)


    @app.route('/2hrArea')
    def get_2hourArea():

    areaWEST = ["Clementi", "Jurong East", "Pioneer", "Boon Lay"]
    areaEAST = ["Tampines", "Changi", "Paya Lebar", "Bedok"]
    areaNORTH = ["Woodlands", "Yishun", "Punggol", "Sembawang"]
    areaSOUTH = ["Harbourfront", "City", "Queenstown", "Bukit Merah"]
    areaCENTRAL = ["Bishan", "Toa Payoh", "Novena"]

    return areaWEST, areaEAST, areaNORTH, areaSOUTH, areaCENTRAL

    @app.route('/2hrForecast')
    def get_2hourForcast():
    twoHrArea = get_twoHourForecast().json()
    twoHrForecast = get_twoHourForecast().json()
    areaWEST, areaEAST, areaNORTH, areaSOUTH, areaCENTRAL = get_2hourArea()

    # Library of the region
    region_dict = {
    "WEST": areaWEST,
    "EAST": areaEAST,
    "NORTH": areaNORTH,
    "SOUTH": areaSOUTH,
    "CENTRAL": areaCENTRAL
    }

    results = []

    #Loop through the twoHrArea list to find the area
    for i, area in enumerate(twoHrArea):
    forecast = twoHrForecast
    region = None

    # Loop through the dictionary's items and it will append the region
    for region_name, areas in region_dict.items():
    if area in areas:
    region = region_name
    break

    #
    if region:
    results.append({
    "area": area,
    "forecast": forecast,
    "region": region
    })

    print(f"{"Area:": area}, {"Forecast:": forecast}, {"Region:": region}")
    return jsonify(results)


    This is my code. Right now whenever I run my code I always get the error for

    twoHrArea = get_twoHourForecast().json()
    twoHrForecast = get_twoHourForecast().json()


    The error message that I got is


    'Response' Object is not subscriptable.
    ​

    How do I solve this issue, as I've tried loads and dumps but to no avail. I'm trying to get out the data from get_twoHourForecast() into an array so that I'm able to compare it with my get_2HourForecast().

    Continue reading...

Compartilhe esta Página