Esempio n. 1
0
def index(request):

    url = ' http://api.openweathermap.org/data/2.5/find?q={}&units=metric&appid=23f5e3d47093431ffabf3d7a5fb65fa9'
    if request.method == "POST":
        form = CityForm(request.POST)
        if form.is_valid():
            c = form.cleaned_data['name']
            count = location.objects.filter(name=c).count()
            if count == 0:
                r = requests.get(url.format(c)).json()
                if r['count'] != 0:
                    form.save()
                    messages.success(request, "City Added Sucessfully")
                else:
                    messages.error(request, "City doesnot exists")
                    return redirect('base')

            else:
                messages.error(request, "City already present")
                return redirect('base')
    form = CityForm()
    a = location.objects.all()
    b = []
    for city in a:
        r = requests.get(url.format(city)).json()

        weather = {
            'city': city.name,
            'temperature': r['list'][0]['main']['temp'],
            'description': r['list'][0]['weather'][0]['description'],
            'icon': r['list'][0]['weather'][0]['icon']
        }
        b.append(weather)
    context = {'b': b, 'form': form}
    return render(request, 'base.html', context)
Esempio n. 2
0
def index_view(request, *args, **kwargs):
    cities = City.objects.all()
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=6bd02d1ff7c484bb30c023666e9004e4'

    if request.method == 'POST':
        print(request)
        form = CityForm(request.POST)
        if form.is_valid():
            form.save()

    form = CityForm()

    weather_data = []

    for city in cities:
        response = requests.get(url.format(city.name))
        if response.ok:
            city_weather = response.json()
        else:
            break

        temp = city_weather['main']['temp'] - 272.15

        weather = {
            'city': city,
            'temperature': temp,
            'description': city_weather['weather'][0]['description'],
            'icon': city_weather['weather'][0]['icon']
        }

        weather_data.append(weather)
    context = {'weather_data': weather_data, 'form': form}
    return render(request, 'index.html', context)
Esempio n. 3
0
def index(request):
    weather_object = None
    if request.method == 'POST':
        form = CityForm( request.POST )
        if form.is_valid():
            logger.info( "process started to fetch data" )
            language = get_language_from_request( request )
            weather_service = OpenWeatherService( settings.OPENWEATHER_URL, q=form.cleaned_data['city'],
                                                  appid=settings.WEATHER_KEY, units="metric", lang=language )
            try:
                weather_object = weather_service.get_data()
                logger.info( "weather information found" )
            except requests.exceptions.HTTPError as e:
                form.add_error( 'city', _( 'Please enter valid city name' ) )
            except requests.exceptions.ConnectionError as e:
                form.add_error( 'city', _( 'System id down. Try in some time' ) )
            except requests.exceptions.Timeout as e:
                form.add_error( 'city', _( 'Server taking too much time to respond. Try in some time' ) )
            except requests.exceptions.RequestException as e:
                form.add_error( 'city', _( 'Please enter valid city name' ) )
    else:
        form = CityForm()

    args = {
        "weather_object": weather_object,
        "form": form
    }
    return render( request, 'weather/index.html', args )
Esempio n. 4
0
def index(request):
    if request.method == 'POST':
        form = CityForm(request.POST, user=request.user)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            form = CityForm(user=request.user)
    else:
        form = CityForm(user=request.user)
    paginator = Paginator(City.objects.filter(user=request.user).order_by('-favorite'), 3)
    cities = paginator.get_page(request.GET.get('page'))
    cities_context = []
    for city in cities:
        city_weather = cache.get(city.name.replace(' ', ''))
        if not city_weather:
            url = API_URL.format(city.name, API_KEY)
            response = requests.get(url)
            city_weather = {
                'temperature': response.json()['main']['temp'],
                'icon': response.json()['weather'][0]['icon']
            }
            cache.set(city.name.replace(" ", ""), city_weather, 300)
        cities_context.append({'city': city, 'weather': city_weather})
    return render(request, 'index.html', {'form': form, 'cities': cities_context, 'paginator': cities,
                                          'pages': range(1, cities.paginator.num_pages+1)})
Esempio n. 5
0
def home(request):
    context = {}
    city = 'amman'
    form = CityForm(request.POST or None)
    if request.is_ajax():
        name = request.GET.get('city', 'amman')
        cities = prepare_cities_json_file(name)
        results = []
        for c in cities:
            results.append(c)
        data = json.dumps(results[:5])
        return HttpResponse(data, 'application/json')

    if request.method == "POST" and form.is_valid():
        city = request.POST.get('name')

    url = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=7da69195ddef314b85013d40d9b594ee&units=metric".format(
        city)
    response = requests.get(url).json()

    city_details = {}
    if response['cod'] == 200:
        city_details = {
            'not_found': False,
            'name': city,
            'description': response['weather'][0]['description'],
            'temp': response['main']['temp'],
            'icon': response['weather'][0]['icon'],
        }
    else:
        city_details['not_found'] = True

    context['city'] = city_details
    context['form'] = form
    return render(request, 'weather/weather.html', context)
Esempio n. 6
0
def index(request):
    owm_api_key = 'owm_api_key'
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid='+owm_api_key
    error_msg = None
    message_class = None

    if request.method == 'POST':
        # print("TRANSMIT ", request.POST)
        form = CityForm(request.POST)

        if form.is_valid():
            new_city = form.cleaned_data['name']
            existing_city_count = CityName.objects.filter(name=new_city).count()
            if existing_city_count == 0:
                response_new = requests.get(url.format(new_city)).json()
                if response_new['cod'] == 200:
                    form.save()
                else:
                    error_msg = "City not found!"
            else:
                error_msg = "City weather is already available!"

        if error_msg:
            message_class = 'is-danger'
        else:
            error_msg = f'Weather of {new_city} fetched successfully!'
            message_class = 'is-success'

        # print("==> ", error_msg, message_class)

    form = CityForm()

    cities = CityName.objects.all()
    weather_data = list()

    for city in cities:
        response = requests.get(url.format(city)).json()
        # print(response.text)

        city_weather = {
            'city': city.name,
            'temperature': response['main']['temp'],
            'description': response['weather'][0]['description'],
            'icon': response['weather'][0]['icon'],
        }

        weather_data.append(city_weather)

    # print(weather_data)
    context = {
                'weather_data': weather_data,
                'form': form,
                'message': error_msg,
                'message_class': message_class
                }

    return render(request, 'weather/weather.html', context=context)
Esempio n. 7
0
def index(request):
    # use the API from WeatherOpenMap
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=ef2d6f3bfd01b0190126858aca4b20eb'
    cities = City.objects.all()
    err_msg = ''
    message = ''
    message_class = ''
    if request.method == "POST":
        form = CityForm(request.POST)

        if form.is_valid():
            # get access to data during request.post

            new_city = form.cleaned_data['name']
            existing_city_count = City.objects.filter(name=new_city).count()
            # check if the city exists in database
            if existing_city_count == 0:
                # check if the city exists in the world
                r = requests.get(url.format(new_city)).json()
                print(r)
                # if code == 404 : the city doesn't exist
                # if the code == 200, the city exists
                if r['cod'] == 200:
                    form.save()
                else:
                    err_msg = "City doesn't exist in the world"
            else:
                err_msg = 'City already exists in the database'

        if err_msg:
            message = err_msg
            message_class = 'is-danger'
        else:
            message = 'City add successfully'
            message_class = 'is-success'

    form = CityForm()
    weather_data = []
    for i in range(len(cities)):
        # format a string
        r = requests.get(url.format(cities[i].name)).json()
        city_weather = {
            'city': cities[i].name,
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon': r['weather'][0]['icon'],
        }
        weather_data.append(city_weather)

    print(weather_data)
    context = {'weather_data': weather_data,
               'form': form,
               'message': message,
               'message_class': message_class
               }
    return render(request, 'weather/weather.html', context, )
Esempio n. 8
0
def climate(request):
    if request.method == 'POST':
        form = CityForm( request.POST )
        if form.is_valid():
            return redirect( climate_for_city, form.cleaned_data['city'] )
    else:
        form = CityForm()

    args = {
        "form": form
    }
    return render( request, 'weather/climate.html', args )
Esempio n. 9
0
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&appid=b67c5e6d6c143bb60dff4f2b7ebe0f96'
    err_msg = ''
    message = ''
    message_class = ''

    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            new_city = form.cleaned_data['name']
            existing_city_count = City.objects.filter(name=new_city).count()

            if existing_city_count == 0:
                r = requests.get(url.format(new_city)).json()
                if r['cod'] == 200:
                    form.save()
                else:
                    err_msg = 'invalid city'
            else:
                err_msg = 'City already exists'
        if err_msg:
            message = err_msg
            message_class = 'is-danger'
        else:
            message = err_msg
            message_class = 'is-success'

    form = CityForm()
    cities = City.objects.all()
    weather_data = []
    for city in cities:
        r = requests.get(url.format(city)).json()
        city_weather = {
            'city': city.name,
            'temperature': r['main']['temp'],
            'description': r['weather'][0]['description'],
            'icon': r['weather'][0]['icon']
        }
        weather_data.append(city_weather)

    print(weather_data)
    context = {
        'weather_data': weather_data,
        'form': form,
        'message': message,
        'message_class': message_class
    }
    return render(request, 'weather/weather.html', context)
Esempio n. 10
0
def home(request):
    we = []
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            form.save()
    for city in Cities.objects.all():
        r = requests.get(url.format(city)).json()
        if (r['cod'] == 200):
            city_w = {
                'city': city,
                'temp': r['main']['temp'],
                'clouds': r['clouds']['all'],
                'weather': r['weather'][0]['description'],
                'temp_min': r['main']['temp_min'],
                'temp_max': r['main']['temp_max'],
            }
            we.append(city_w)
    form = CityForm()
    context = {'we': we, 'form': form}
    return render(request, 'home.html', context)
Esempio n. 11
0
def index(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=006c89cde1c1914e319a96dc02446ab9'
    cities = City.objects.all()
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('weather:home'))
    else:
        form = CityForm()
    weather_data = []
    for city in cities:
        city_weather = requests.get(url.format(city)).json()
        weather = {
            'city': city,
            'temperature': city_weather['main']['temp'],
            'description': city_weather['weather'][0]['description'],
            'icon': city_weather['weather'][0]['icon']
        }
        weather_data.append(weather)
    context = {'weather_data': weather_data, 'form': form}
    return render(request, 'weather/index.html', context)
Esempio n. 12
0
def no_data(request):
    form = CityForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('forecast')
    a = 1
    url_m = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=3e8c61a2a241410b6fa72b0186291c90'
    value = []
    main_data = []
    while a < 7:
        main_city = str(MainCities.objects.get(pk=a))
        m = requests.get(url_m.format(main_city)).json()
        main_cities = {
            'city': main_city,
            'icon': m['weather'][0]['icon'],
            'country': m['sys']['country'],
            'temp': round(m['main']['temp'], 1),
            'timezone': m['timezone'],
            'dt': m['dt'],
            'utc': m['timezone'] / 3600
        }

        a += 1
        main_data.append(main_cities)
        country_codes = main_data[a - 2]["country"]
        country_timezones = pytz.country_timezones[country_codes]
        country_timezone = country_timezones[0]
        current_time = datetime.now(pytz.timezone(country_timezone))
        asd = current_time.strftime('%H:%M')
        value.append(asd)

    return render(request, 'weather/no_data.html', {
        "form": form,
        "main_data": main_data,
        "value": value
    })
Esempio n. 13
0
    def test_city_form_valid_data(self):
        form = CityForm(data={"name": "Sopot"})

        self.assertTrue(form.is_valid())
Esempio n. 14
0
    def test_city_form_no_data(self):
        form = CityForm(data={})

        self.assertFalse(form.is_valid())
        self.assertEquals(len(form.errors), 1)
Esempio n. 15
0
 def test_weather_request_ru(self):
     """ Проверка ввода города на Русском """
     form = CityForm({"City": "Лондон"})
     form.is_valid()
     city = form.cleaned_data['City']
     self.assertEqual(city, "Лондон")
Esempio n. 16
0
 def test_weather_request_en(self):
     """ Проверка ввода города на Английском """
     form = CityForm({"City": "London"})
     form.is_valid()
     city = form.cleaned_data['City']
     self.assertEqual(city, "London")
Esempio n. 17
0
def forecast(request):
    form = CityForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        form.save()
        return redirect('forecast')
    a = 1

    url_m = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=3e8c61a2a241410b6fa72b0186291c90'
    value = []
    main_data = []
    while a < 7:
        main_city = str(MainCities.objects.get(pk=a))
        m = requests.get(url_m.format(main_city)).json()

        main_cities = {
            'city': main_city,
            'icon': m['weather'][0]['icon'],
            'country': m['sys']['country'],
            'temp': round(m['main']['temp'], 1),
            'timezone': m['timezone'],
            'dt': m['dt'],
            'utc': m['timezone'] / 3600
        }

        a += 1
        main_data.append(main_cities)
        country_codes = main_data[a - 2]["country"]
        country_timezones = pytz.country_timezones[country_codes]
        country_timezone = country_timezones[0]
        current_time = datetime.now(pytz.timezone(country_timezone))
        asd = current_time.strftime('%H:%M')
        value.append(asd)

    city_count = City.objects.count()
    if city_count == 0:
        return redirect('main')

    else:
        cityy = City.objects.last()
        city = str(cityy).title()
        url_c = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=3e8c61a2a241410b6fa72b0186291c90'

        c = requests.get(url_c.format(city)).json()
    try:
        current = {
            'city': city,
            'lon': c['coord']['lon'],
            'lat': c['coord']['lat'],
            'description': c['weather'][0]['description'],
            'icon': c['weather'][0]['icon'],
            'temp': round(c['main']['temp'], 1),
            'feels_like': round(c['main']['feels_like'], 1),
            'temp_min': c['main']['temp_min'],
            'temp_max': c['main']['temp_max'],
            'pressure': c['main']['pressure'],
            'humidity': c['main']['humidity'],
            'wind': c['wind']['speed'],
            'deg': c['wind']['deg'],
            'name': c['name'],
            'timezone': c['timezone'],
            'utc': c['timezone'] / 3600,
            'dt': c['dt'],
        }

        gr = current['dt']
        readable = datetime.fromtimestamp(gr).isoformat()
        date = readable[0:10]
        dateb = {'date': date}
        current.update(dateb)
        wind_deg = current['deg']
        dirs = [
            'North', 'North-northeast', 'Northeast', 'East-northeast', 'East',
            'East-southeast', 'Southeast', 'South-southeast', 'South',
            'South-southwest', 'Southwest', 'West-southwest', 'West',
            'West-northwest', 'Northwest', 'North-northwest'
        ]
        ix = round(wind_deg / (360. / len(dirs)))
        ixx = dirs[ix % len(dirs)]
        dir_dic = {'dir': ixx}
        current.update(dir_dic)
    except KeyError:
        return redirect('no_data')

    url = 'http://api.openweathermap.org/data/2.5/forecast?q={}&units=metric&appid=3e8c61a2a241410b6fa72b0186291c90'
    r = requests.get(url.format(city)).json()
    a = 0
    list = []
    weather_data = []
    first_day = []
    second_day = []
    third_day = []
    fourth_day = []
    fifth_day = []
    sixth_day = []
    while a < 40:
        weather_forecast = {
            'city': city,
            'data': r['list'][a]['dt_txt'][5:16],
            'day': r['list'][a]['dt_txt'][5:10],
            'description': r['list'][a]['weather'][0]['description'],
            'icon': r['list'][a]['weather'][0]['icon'],
            'wind': r['list'][a]['wind']['speed'],
            'temperature': round(r['list'][a]['main']['temp'], 1),
            'feels_like': r['list'][a]['main']['feels_like'],
            'temp_min': r['list'][a]['main']['temp_min'],
            'pressure': r['list'][a]['main']['pressure'],
            'humidity': r['list'][a]['main']['humidity'],
        }
        a += 1
        weather_data.append(weather_forecast)
        list.append(weather_forecast['day'])

    first = list.count(list[0])
    second = list.count(list[first])
    third = list.count(list[second + first])
    fourth = list.count(list[third + second + first])
    fifth = list.count(list[fourth + third + second + first])
    sixth = list.count(list[fifth + fourth + third + second + first])

    first_day.append(weather_data[0:first])
    second_day.append(weather_data[first:second + first])
    third_day.append(weather_data[second + first:third + second + first])
    fourth_day.append(weather_data[third + second + first:fourth + third +
                                   second + first])
    fifth_day.append(weather_data[fourth + third + second + first:fifth +
                                  fourth + third + second + first])
    sixth_day.append(weather_data[fifth + fourth + third + second + first:])

    first_day = first_day[0]
    second_day = second_day[0]
    third_day = third_day[0]
    fourth_day = fourth_day[0]
    fifth_day = fifth_day[0]
    sixth_day = sixth_day[0]

    from datetime import date, timedelta

    tomo = date.today() - timedelta(-2)
    to = tomo.strftime('%A')
    third_day[0].update({'day_name': to})

    t_days = date.today() - timedelta(-3)
    td = t_days.strftime('%A')
    fourth_day[0].update({'day_name': td})

    fr_days = date.today() - timedelta(-4)
    tfr = fr_days.strftime('%A')
    fifth_day[0].update({'day_name': tfr})

    s_days = date.today() - timedelta(-5)
    ts = s_days.strftime('%A')
    sixth_day[0].update({'day_name': ts})

    context = {
        'current': current,
        'weather_data': weather_data,
        'city': city,
        "form": form,
        "main_data": main_data,
        "value": value,
        'first_day': first_day,
        'second_day': second_day,
        'third_day': third_day,
        'fourth_day': fourth_day,
        'fifth_day': fifth_day,
        'sixth_day': sixth_day
    }

    if city_count > 10:
        City.objects.filter().first().delete()
    else:
        pass
    return render(request, 'weather/forecast.html', context)
Esempio n. 18
0
    def test_form_is_valid(self):
        form = CityForm(data={'name': 'nairobi'})

        self.assertTrue(form.is_valid())
Esempio n. 19
0
    def test_form_is_invalid(self):
        form = CityForm(data={})

        self.assertFalse(form.is_valid())