import json from flask import Flask, render_template, request from datetime import datetime, date import requests url = 'https://covidtrackerapi.bsg.ox.ac.uk/api/v2/stringency/actions/' ''' 01. Belarus - BLR 02. China - CHN 03. France - FRA 04. Germany - DEU 05. India - IND 06. Israel - ISR 07. Russia - RUS 08. Serbia - SRB 09. Spain - ESP 10. Turkey - TUR ''' countries = ['blr', 'chn', 'fra', 'deu', 'ind', 'isr', 'rus', 'srb', 'esp', 'tur'] tmp_output = {} def check_date(input_date): """ Check date format from input string. Args: input_date - (str). Return: Bool - True if date correct. """ try: # valid_date = datetime.strptime(input_date, '%Y-%m-%d').date() datetime.strptime(input_date, '%Y-%m-%d').date() return True except ValueError: return False def request_one_country(api, cntr, day): """ Request from api-url. Args: api - (str) - api url, cntr - (str) country alpha-3 code, day - (int) YYYY-MM-DD. Return: Response - (dict). """ r_out = requests.get(f'{api}{cntr}/{day}') return r_out.json() ###################################################### app = Flask(__name__) @app.route('/', methods=['post', 'get']) def index(): if request.method == 'POST': input_date = request.form.get('input_date') # запрос к данным формы if check_date(input_date): correct_date = datetime.strptime(input_date, '%Y-%m-%d').date() if correct_date >= date.today(): return render_template('index.html', message='Input date has not arrived yet') for country in countries: out = request_one_country(url, country, correct_date) tmp_output.setdefault(country, out.get('stringencyData')) output = {input_date: tmp_output} with open('../temp_out.json', 'w') as f: json.dump(output, f, sort_keys=True, indent=2) return render_template('index.html') elif not input_date: return render_template('index.html', message='Please input date') else: return render_template('index.html', message='Incorrect input') else: return render_template('index.html') if __name__ == "__main__": app.run(host='127.0.0.1', port=8181, debug=True)