示例#1
0
def create_response():
    form = CityForm()
    errors = []
    context = {'form': form, 'city': 'Москва'}
    if form.validate_on_submit():
        city = form.city_name.data
        context.update({'city': city})
        res = requests.post(
            'http://api.openweathermap.org/data/2.5/weather?q={}&type=like&units=metric&APPID=7ac3ad468ed360aa275f1bcac7c85e9b&lang=ru'
            .format(city))
        jsonData = res.json()
        code_from_api = jsonData['cod']
        if form.validate_city(code_from_api):
            temperature = str(jsonData['main']['temp'])
            if jsonData['main']['temp'] > 0:
                temperature = '+' + temperature
            feels_like = str(jsonData['main']['feels_like'])
            if jsonData['main']['feels_like'] > 0:
                feels_like = '+' + feels_like
            timestamp = jsonData['dt']
            dt = datetime.datetime.fromtimestamp(timestamp).strftime(
                '%H:%M:%S %d.%m.%Y')
            cond = {
                'perception': (jsonData['main']['feels_like'] < 10),
                'humidity': (jsonData['main']['humidity'] > 30),
                'wind': ((-jsonData['main']['temp'] - 6 +
                          (5 / 6) * jsonData['wind']['speed']) > 0) |
                (jsonData['wind']['speed'] > 5) |
                (jsonData['main']['temp'] < 5)
            }
            context.update({
                'weather':
                str(jsonData['weather'][0]['description']),
                'coord':
                jsonData['coord'],
                'country':
                countries.get(jsonData['sys']['country']).name,
                'temp':
                temperature,
                'feels_like':
                feels_like,
                'humidity':
                str(jsonData['main']['humidity']),
                'speed':
                str(jsonData['wind']['speed']),
                'cond':
                cond,
                'dt':
                str(dt),
                'img':
                jsonData['weather'][0]['icon']
            })
            return render_template('weather.html', **context)
        errors.extend(form.city_name.errors)
        context.update({'errors': errors})
        return render_template('weather.html', **context)
    errors.extend(form.city_name.errors)
    context.update({'errors': errors})
    return render_template('weather.html', **context)
示例#2
0
def city():
    form = CityForm()
    if form.validate_on_submit():
        flash('Getting that for city {}'.format(form.city.data))
        city = {'name': form.city.data}
        state = {'name': form.state.data}
        url_data = "http://api.openweathermap.org/data/2.5/weather?q=Bristol,uk&appid=be1eadecdcbaa82aa548e731c8d230f4"
        webUrl = urllib.request.urlopen(url_data)
        json_data = json.loads(webUrl.read())
        #print(json_data)
        return render_template('/todays_weather.html', city=city)
    return render_template('city_weather.html', title='Party City', form=form)
示例#3
0
def login():
    #iso = pd.read_excel('/static/iso3166_rus.xlsx')
    #iso.drop('Numeric', inplace=True)
    #iso['Country_en'] = [countries.get(row).name for row in iso['Alpha-2']]
    #choices = [", ".join(e for e in list) for list in iso[['Alpha-3','Country','Country_en']].values.tolist()]
    with open('C:/Users/d9ld9/github/weatherin/app/countries.json', 'r') as f:
        country_data = json.loads(json.load(f))
    choices = [(elem['Alpha-2'], elem['Country_en']) for elem in country_data]
    form = CityForm()
    form.country_choice.choices = choices
    errors = []
    context = {'form': form, 'city': 'Москва', 'country': '--optional--'}
    if form.validate_on_submit():
        city = form.city_name.data
        country = form.country_choice.data
        lang = [tup[0] for tup in choices if tup[1] == country]
        context.update({'city': city, 'country': country, 'lang': lang[0]})
        res = requests.post(
            'http://api.openweathermap.org/data/2.5/weather?q={}&type=like&units=metric&APPID=7ac3ad468ed360aa275f1bcac7c85e9b&lang=ru'
            .format(city))
        jsonData = res.json()
        code = jsonData['cod']
        if form.validate_city(code):
            errors.extend(form.city_name.errors)
            context.update({'errors': errors})
            return render_template('weather.html', **context)
        errors.extend(form.city_name.errors)
        temp = str(jsonData['main']['temp'])
        if jsonData['main']['temp'] > 0:
            temp = '+' + temp
        feels_like = str(jsonData['main']['feels_like'])
        if jsonData['main']['feels_like'] > 0:
            feels_like = '+' + feels_like
        timestamp = jsonData['dt']
        dt = datetime.datetime.fromtimestamp(timestamp).strftime(
            '%H:%M:%S %d.%m.%Y')
        context.update({
            'errors': errors,
            'weather': str(jsonData['weather'][0]['description']),
            'coord': jsonData['coord'],
            'country': countries.get(jsonData['sys']['country']).name,
            'temp': temp,
            'feels_like': feels_like,
            'humidity': str(jsonData['main']['humidity']),
            'speed': str(jsonData['wind']['speed']),
            'dt': str(dt),
            'img': jsonData['weather'][0]['icon']
        })
        return render_template('weather.html', **context)
    return render_template('weather.html', **context)
示例#4
0
def search_results():
    form = CityForm()
    if form.search.data is not None:
        results = z_cities.query.filter(
            z_cities.RegionName.like('%' + form.search.data))
        return render_template('search_results.html',
                               results=results,
                               form=form)
    else:
        results = db.engine.execute("SELECT z_cities.RegionName FROM z_cities")
        return render_template('cities.html', results=results, form=form)
示例#5
0
def top_searches():
    city_form = CityForm(request.form)

    from collections import Counter, OrderedDict
    top_searches = Counter(locations_counter)
    ordered_top_searches = OrderedDict(top_searches.most_common())
    total_searches = sum(top_searches.values())

    return render_template("top-searches.html",
                           city_form=city_form,
                           ordered_top_searches=ordered_top_searches,
                           total_searches=total_searches)
示例#6
0
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid='+api_key
    cities = City.objects.all() # return all the cities in the DB
    
    if(request.method == "POST"): # Only true if form is submitted
        form = CityForm(request.POST)  # add actual request data to form for processing
        form.save() # will validate and save if validate

    form = CityForm()

    weather_data = []
    city_names = []

    for city in cities:
        if(city.name in city_names):
            city.delete()
        else:
            city_names.append(city.name)
            city_weather = requests.get(url.format(city)).json()
            if(city_weather["cod"] != "404"):
                weather = {
                    "city": city,
                    'temperature' : city_weather['main']['temp'],
                    'description' : city_weather['weather'][0]['description'],
                    'icon' : city_weather['weather'][0]['icon']
                }
                weather_data.append(weather)
            else:
                city.delete()

    context = {"weather_data" : weather_data, "form": form}

    return render(request, 'app/index.html', context=context)
示例#7
0
def citylookup():
    API_KEY = app.config['WEATHER_API_KEY']
    # print(API_KEY)
    city = 'boston'

    form = CityForm()

    if form.validate_on_submit():

        city = form.city.data

        state = form.city.data

        city = city + "," + state + ",US"
        print(city)

    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&APPID={API_KEY}&units=imperial'

    #json() method convets string response into python dictionary
    response = requests.get(url).json()

    print(response)
    return render_template('citylookup.html', form=form, response=response)
示例#8
0
def home(request):
    form = CityForm()

    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            form.save()
            city_name = form.cleaned_data.get('city_name')
            weather_data = get_weather_data(city_name)
    elif request.method == 'GET':
        try:
            city_name = City.objects.latest('date_added').city_name
            weather_data = get_weather_data(city_name)
        except Exception:
            weather_data = None
    return render(request, 'home.html', {
        'form': form,
        'weather_data': weather_data
    })
示例#9
0
def cities():
    form = CityForm()

    #cities1=db.engine.execute("SELECT z_cities.MSAName FROM z_cities")

    return render_template('cities.html', form=form)
示例#10
0
def home():
    city_form = CityForm(request.form)

    # Handling POST request when CityForm is submitted
    if request.method == "POST":
        corrected_user_query_location = city_form.location.data.replace(
            " ", "%20")
        nominatim_api = get(
            f"https://nominatim.openstreetmap.org/search/"
            f"{corrected_user_query_location}?format=json").json()
        location_lat = nominatim_api[0]["lat"]
        location_lon = nominatim_api[0]["lon"]

        apis_responses = call_apis(location_lat, location_lon)

        apis_data = store_data_from(apis_responses["opwm_cel_api"],
                                    apis_responses["opwm_fah_api"],
                                    apis_responses["opwm_cel_forecast_api"],
                                    apis_responses["opwm_fah_forecast_api"],
                                    apis_responses["opwm_uv_index_api"],
                                    apis_responses["timezonedb_api"],
                                    apis_responses["air_quality_api"])

        locations_counter.append(city_form.location.data.split(",")[0].title())
        locations_counter.reverse()

        cache.set("locations_counter", locations_counter)

        user_recent_locations_data.append([
            city_form.location.data.split(",")[0].title(),
            apis_data["country_code"], apis_data["weather_cel_temp_current"],
            apis_data["weather_cel_icon_current"],
            apis_data["weather_description"]
        ])
        user_recent_locations_data.reverse()

        cache.set("user_recent_locations_data", user_recent_locations_data)

        city_form.location.data = ""

        return render_template("dashboard.html",
                               location_lat=location_lat,
                               location_lon=location_lon,
                               apis_data=apis_data,
                               cache=cache,
                               city_form=city_form)

    # Handling GET request when the 'location' parameter is used in the URL
    elif request.method == "GET" and request.args.get("location"):
        corrected_user_query_location = request.args.get("location").replace(
            " ", "%20")
        nominatim_api = get(
            f"https://nominatim.openstreetmap.org/search/"
            f"{corrected_user_query_location}?format=json").json()
        location_lat = nominatim_api[0]["lat"]
        location_lon = nominatim_api[0]["lon"]

        apis_responses = call_apis(location_lat, location_lon)

        apis_data = store_data_from(apis_responses["opwm_cel_api"],
                                    apis_responses["opwm_fah_api"],
                                    apis_responses["opwm_cel_forecast_api"],
                                    apis_responses["opwm_fah_forecast_api"],
                                    apis_responses["opwm_uv_index_api"],
                                    apis_responses["timezonedb_api"],
                                    apis_responses["air_quality_api"])

        locations_counter.append(request.args.get("location"))
        locations_counter.reverse()

        cache.set("locations_counter", locations_counter)

        user_recent_locations_data.append([
            request.args.get("location"), apis_data["country_code"],
            apis_data["weather_cel_temp_current"],
            apis_data["weather_cel_icon_current"],
            apis_data["weather_description"]
        ])
        user_recent_locations_data.reverse()

        cache.set("user_recent_locations_data", user_recent_locations_data)

        city_form.location.data = ""

        return render_template("dashboard.html",
                               location_lat=location_lat,
                               location_lon=location_lon,
                               apis_data=apis_data,
                               cache=cache,
                               city_form=city_form)

    # Handling GET request with no parameter
    return render_template("home.html", cache=cache, city_form=city_form)
示例#11
0
def about():
    city_form = CityForm(request.form)
    return render_template("about.html", city_form=city_form)
示例#12
0
def changelog():
    city_form = CityForm(request.form)
    return render_template("changelog.html", city_form=city_form)
示例#13
0
def map():
    city_form = CityForm(request.form)

    return render_template("map.html", city_form=city_form)