aboutsummaryrefslogtreecommitdiff
path: root/src/app.py
diff options
context:
space:
mode:
Diffstat (limited to 'src/app.py')
-rw-r--r--src/app.py72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/app.py b/src/app.py
new file mode 100644
index 0000000..6426b04
--- /dev/null
+++ b/src/app.py
@@ -0,0 +1,72 @@
1#!/usr/bin/env python3
2import json, requests, datetime, argparse, pytz, flask
3import library, forms
4
5app = flask.Flask(__name__)
6app.config['SECRET_KEY'] = "JAnmklasd39u2mnwim"
7
8
9def check_submission(location):
10 latitude, longitude = library.get_lat_long(location)
11 if (latitude, longitude) == (0, 0):
12 return flask.redirect(flask.url_for('location', location=location))
13 else:
14 return flask.redirect(flask.url_for('weather', latitude=latitude, longitude=longitude))
15
16
17@app.route('/', methods=('GET','POST'))
18def index():
19 form = forms.WeatherForm()
20 if form.validate_on_submit():
21 location = form.location.data
22 return check_submission(location)
23 else:
24 return flask.render_template("index.html", form=form)
25
26
27@app.route('/weather', methods=('GET','POST'))
28def weather():
29 latitude = flask.request.args.get('latitude', type=str)
30 longitude = flask.request.args.get('longitude', type=str)
31 data = library.get_data(latitude, longitude)
32 hour = library.get_current_rounded_time(data["timezone"]).hour
33 form = forms.WeatherForm()
34 if form.validate_on_submit():
35 location = form.location.data
36 return check_submission(location)
37 else:
38 return flask.render_template("weather.html", data=data, form=form, weather_codes=library.weather_codes, datetime=datetime,
39 weather_icons=library.weather_icons, hour=hour, get_direction_icon=library.get_direction_icon)
40
41
42@app.route('/location', methods=('GET','POST'))
43def location():
44 location = flask.request.args.get('location', type=str)
45 url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=10&language=en&format=json"
46 headers = {"User-Agent": "pywttr 0.1"}
47 data = requests.get(url, headers=headers).json()
48
49 choices = []
50 for i in range(len(data["results"])):
51 point = data["results"][i]
52 choice_str = point["name"] + ", "
53 if "admin1" in point:
54 choice_str += point["admin1"] + ", "
55 if "country" in point:
56 choice_str += point["country"]
57 choices.append((i, choice_str))
58
59 form = forms.LocationForm()
60 form.location.choices = choices
61 form.location.default = choices[0]
62 if form.is_submitted():
63 location = data["results"][int(form.location.data)]
64 latitude = location["latitude"]
65 longitude = location["longitude"]
66 return flask.redirect(flask.url_for('weather', latitude=latitude, longitude=longitude))
67 else:
68 return flask.render_template("location.html", data=data, form=form)
69
70
71if __name__ == "__main__":
72 app.run(debug=True)