Im making a python weather webb app with flask that gathers data from an API key but im having issues

I get the data from the API key that’s stored in a venv file. I can request the weather of the date to be shown but it shows up as

” Temperature: N/A°C / N/A°F

Condition: N/A “

When I try and run the app with “flask run” through the terminal it fetches the data from the API, but through a JSON object that contains nested information. The problem is to display the data in a user-friendly format.

Here’s the code of the three files, the python file, the weather.html file and the index.html file.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from flask import Flask, render_template, request
import os
from dotenv import load_dotenv
import requests
# Load environment variables from .env file
load_dotenv()
app = Flask(__name__)
@app.route('/')
def index():
api_key = os.getenv('WEATHER_API_KEY') # Ensure this is not a real key
return render_template('index.html', api_key=api_key)
@app.route('/weather_app', methods=['POST'])
def weather_app():
date = request.form.get('date')
api_key = os.getenv('WEATHER_API_KEY') # Ensure this is not a real key
api_url = "https://api.weatherapi.com/v1/history.json"
params = {
'key': api_key,
'q': "Stockholm",
'dt': date
}
response = requests.get(api_url, params=params)
if response.status_code == 200:
weather_data = response.json()
location = weather_data.get('location', {})
current = weather_data.get('current', {})
location_name = location.get('name', 'Unknown')
temp_c = current.get('temp_c', 'N/A')
temp_f = current.get('temp_f', 'N/A')
condition_text = current.get('condition', {}).get('text', 'N/A')
condition_icon = current.get('condition', {}).get('icon', '')
formatted_data = {
'location_name': location_name,
'temp_c': temp_c,
'temp_f': temp_f,
'condition_text': condition_text,
'condition_icon': condition_icon,
'date': date
}
return render_template('weather.html', weather=formatted_data)
else:
return f"Error: Unable to fetch weather data (Status Code: {response.status_code})"
if __name__ == '__main__':
app.run(debug=True)
</code>
<code>from flask import Flask, render_template, request import os from dotenv import load_dotenv import requests # Load environment variables from .env file load_dotenv() app = Flask(__name__) @app.route('/') def index(): api_key = os.getenv('WEATHER_API_KEY') # Ensure this is not a real key return render_template('index.html', api_key=api_key) @app.route('/weather_app', methods=['POST']) def weather_app(): date = request.form.get('date') api_key = os.getenv('WEATHER_API_KEY') # Ensure this is not a real key api_url = "https://api.weatherapi.com/v1/history.json" params = { 'key': api_key, 'q': "Stockholm", 'dt': date } response = requests.get(api_url, params=params) if response.status_code == 200: weather_data = response.json() location = weather_data.get('location', {}) current = weather_data.get('current', {}) location_name = location.get('name', 'Unknown') temp_c = current.get('temp_c', 'N/A') temp_f = current.get('temp_f', 'N/A') condition_text = current.get('condition', {}).get('text', 'N/A') condition_icon = current.get('condition', {}).get('icon', '') formatted_data = { 'location_name': location_name, 'temp_c': temp_c, 'temp_f': temp_f, 'condition_text': condition_text, 'condition_icon': condition_icon, 'date': date } return render_template('weather.html', weather=formatted_data) else: return f"Error: Unable to fetch weather data (Status Code: {response.status_code})" if __name__ == '__main__': app.run(debug=True) </code>
from flask import Flask, render_template, request
import os
from dotenv import load_dotenv
import requests

# Load environment variables from .env file
load_dotenv()

app = Flask(__name__)

@app.route('/')
def index():
    api_key = os.getenv('WEATHER_API_KEY')  # Ensure this is not a real key
    return render_template('index.html', api_key=api_key)

@app.route('/weather_app', methods=['POST'])
def weather_app():
    date = request.form.get('date')
    api_key = os.getenv('WEATHER_API_KEY')  # Ensure this is not a real key

    api_url = "https://api.weatherapi.com/v1/history.json"
    params = {
        'key': api_key,
        'q': "Stockholm",
        'dt': date
    }

    response = requests.get(api_url, params=params)

    if response.status_code == 200:
        weather_data = response.json()
        
        location = weather_data.get('location', {})
        current = weather_data.get('current', {})
        
        location_name = location.get('name', 'Unknown')
        temp_c = current.get('temp_c', 'N/A')
        temp_f = current.get('temp_f', 'N/A')
        condition_text = current.get('condition', {}).get('text', 'N/A')
        condition_icon = current.get('condition', {}).get('icon', '')
        
        formatted_data = {
            'location_name': location_name,
            'temp_c': temp_c,
            'temp_f': temp_f,
            'condition_text': condition_text,
            'condition_icon': condition_icon,
            'date': date
        }

        return render_template('weather.html', weather=formatted_data)
    else:
        return f"Error: Unable to fetch weather data (Status Code: {response.status_code})"

if __name__ == '__main__':
    app.run(debug=True)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather Data</title>
</head>
<body>
<h1>Weather Data for {{ weather.date }}</h1>
<p>Location: {{ weather.location_name }}</p>
<p>Temperature: {{ weather.temp_c }}°C / {{ weather.temp_f }}°F</p>
<p>Condition: {{ weather.condition_text }}</p>
<img src="https://cdn.weatherapi.com/weather/64x64/{{ weather.condition_icon }}" alt="Weather Icon">
<a href="/">Go back</a>
</body>
</html>
</code>
<code><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Weather Data</title> </head> <body> <h1>Weather Data for {{ weather.date }}</h1> <p>Location: {{ weather.location_name }}</p> <p>Temperature: {{ weather.temp_c }}°C / {{ weather.temp_f }}°F</p> <p>Condition: {{ weather.condition_text }}</p> <img src="https://cdn.weatherapi.com/weather/64x64/{{ weather.condition_icon }}" alt="Weather Icon"> <a href="/">Go back</a> </body> </html> </code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather Data</title>
</head>
<body>
    <h1>Weather Data for {{ weather.date }}</h1>
    <p>Location: {{ weather.location_name }}</p>
    <p>Temperature: {{ weather.temp_c }}°C / {{ weather.temp_f }}°F</p>
    <p>Condition: {{ weather.condition_text }}</p>
    <img src="https://cdn.weatherapi.com/weather/64x64/{{ weather.condition_icon }}" alt="Weather Icon">
    <a href="/">Go back</a>
</body>
</html>
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Weather App</title>
</head>
<body>
<h1>Weather App</h1>
<form action="/weather_app" method="POST">
<label for="date">Enter a date (YYYY-MM-DD):</label>
<input type="text" id="date" name="date" required>
<button type="submit">Get Weather</button>
</form>
<p>Weather API Key: {{ api_key }}</p> <!-- Ensure API key is a placeholder -->
</body>
</html>
</code>
<code><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Weather App</title> </head> <body> <h1>Weather App</h1> <form action="/weather_app" method="POST"> <label for="date">Enter a date (YYYY-MM-DD):</label> <input type="text" id="date" name="date" required> <button type="submit">Get Weather</button> </form> <p>Weather API Key: {{ api_key }}</p> <!-- Ensure API key is a placeholder --> </body> </html> </code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Weather App</title>
</head>
<body>
    <h1>Weather App</h1>
    <form action="/weather_app" method="POST">
        <label for="date">Enter a date (YYYY-MM-DD):</label>
        <input type="text" id="date" name="date" required>
        <button type="submit">Get Weather</button>
    </form>
    <p>Weather API Key: {{ api_key }}</p>  <!-- Ensure API key is a placeholder -->
</body>
</html>

Please bear with me if Im explaining this in a bad way or leaving any information out.

I fetched weather data from an API using flask and attempted to display it on a webpage.

I expected the weather data (like temperature and condition) to be displayed in a user-friendly format on the webpage.

New contributor

Seblan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật