#!/usr/bin/env python3 import json import requests import datetime import argparse import pytz import flask import library import forms app = flask.Flask(__name__) app.config['SECRET_KEY'] = "JAnmklasd39u2mnwim" def check_submission(location): latitude, longitude = library.get_lat_long(location) if (latitude, longitude) == (0, 0): return flask.redirect(flask.url_for('location', location=location)) else: return flask.redirect(flask.url_for('weather', latitude=latitude, longitude=longitude)) @app.route('/', methods=('GET', 'POST')) def index(): form = forms.WeatherForm() if form.validate_on_submit(): location = form.location.data return check_submission(location) else: return flask.render_template("index.html", form=form) @app.route('/weather', methods=('GET', 'POST')) def weather(): latitude = flask.request.args.get('latitude', type=str) longitude = flask.request.args.get('longitude', type=str) data = library.get_data(latitude, longitude) hour = library.get_current_rounded_time(data["timezone"]).hour form = forms.WeatherForm() if form.validate_on_submit(): location = form.location.data return check_submission(location) else: return flask.render_template("weather.html", data=data, form=form, weather_codes=library.weather_codes, datetime=datetime, weather_icons=library.weather_icons, hour=hour, get_direction_icon=library.get_direction_icon) @app.route('/location', methods=('GET', 'POST')) def location(): location = flask.request.args.get('location', type=str) url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=10&language=en&format=json" headers = {"User-Agent": "pywttr 0.1"} data = requests.get(url, headers=headers).json() choices = [] for i in range(len(data["results"])): point = data["results"][i] choice_str = point["name"] + ", " if "admin1" in point: choice_str += point["admin1"] + ", " if "country" in point: choice_str += point["country"] choices.append((i, choice_str)) form = forms.LocationForm() form.location.choices = choices form.location.default = choices[0] if form.is_submitted(): location = data["results"][int(form.location.data)] latitude = location["latitude"] longitude = location["longitude"] return flask.redirect(flask.url_for('weather', latitude=latitude, longitude=longitude)) else: return flask.render_template("location.html", data=data, form=form) if __name__ == "__main__": app.run(debug=True)