59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
from flask import Flask, jsonify, request, render_template
|
|
from wetterdienst.provider.dwd.observation import DwdObservationRequest, DwdObservationResolution
|
|
from wetterdienst.util.geo import Coordinates
|
|
from geopy.geocoders import Nominatim
|
|
from datetime import datetime, timedelta
|
|
|
|
app = Flask(__name__, static_folder='static', template_folder='templates')
|
|
|
|
# Function to get coordinates based on the user location
|
|
def get_coordinates(location):
|
|
geolocator = Nominatim(user_agent="wetterdienst_app")
|
|
location = geolocator.geocode(location)
|
|
if location:
|
|
return Coordinates(location.latitude, location.longitude)
|
|
return None
|
|
|
|
# Function to get weather data from DWD API
|
|
def get_weather_data(location):
|
|
coords = get_coordinates(location)
|
|
if not coords:
|
|
return {"error": "Location not found."}
|
|
|
|
request = DwdObservationRequest(
|
|
parameter=["temperature_air_mean_200", "precipitation_height", "wind_speed"],
|
|
resolution=DwdObservationResolution.HOURLY,
|
|
start_date=(datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d"),
|
|
end_date=(datetime.now() + timedelta(days=10)).strftime("%Y-%m-%d")
|
|
)
|
|
|
|
stations = request.filter_by_distance(latlon=(coords.latitude, coords.longitude), distance=30)
|
|
values = stations.values.all().df
|
|
|
|
if values.empty:
|
|
return {"error": "No data available for the selected location."}
|
|
|
|
weather_data = values.to_dict(orient='records')
|
|
return weather_data
|
|
|
|
# Route for rendering the HTML frontend
|
|
@app.route('/')
|
|
def index():
|
|
return render_template('index.html')
|
|
|
|
# API endpoint for fetching weather data based on user input
|
|
@app.route('/api/weather', methods=['GET'])
|
|
def weather():
|
|
location = request.args.get('location')
|
|
if not location:
|
|
return jsonify({"error": "Please provide a location."}), 400
|
|
|
|
data = get_weather_data(location)
|
|
if "error" in data:
|
|
return jsonify(data), 404
|
|
|
|
return jsonify(data)
|
|
|
|
if __name__ == '__main__':
|
|
app.run(host='0.0.0.0', port=5000)
|