Exemple #1
0
 def test_city_is_related_to_list(self):
     list_ = List.objects.create()
     city = City(
         name='City',
         list=list_,
     )
     city.save()
     self.assertIn(city, list_.city_set.all())
Exemple #2
0
def delete_record(id):
    # Удаление записи из БД
    if request.method == 'POST':
        try:
            City.delete_city(
                id)  # Обращение к методу delete_city для удаления из БД
            flash('Record deleted', 'danger')
            current_app.logger.warning('Record deleted')
        except:
            flash('Something has gone wrong',
                  'danger')  # Уведомление в случае неудачного удаления записи
        return redirect('/index')
 def test_cannot_save_empty_city(self):
     list_ = List.objects.create()
     city = City()
     city.name = ''
     city.list = list_
     with self.assertRaises(ValidationError):
         city.save()
         city.full_clean()
Exemple #4
0
    def get(self, request, id=0):
        warning_message = create_warning_message(request.user)
        form = CityForm()
        city_message = ""
        if id:  # city-list.html
            user = User.objects.get(id=id)
            current_profile = Profile.objects.get_or_create(
                user=user)[0]  # User is authorised
            for city in current_profile.cities.all():
                update_weather_if_needed(city)
            cities_list = current_profile.cities.all(
            )  # Get updated list of cities
            available = True if cities_list else False  # False if empty
            info = {
                'available': available,
                'cities_list': cities_list,
            }
            template_name = 'city_list.html'

        else:  # weather_info.html
            city = City()
            info = {
                'available': False,
                'city': city,
            }
            template_name = 'weather_in_city.html'
        result = render(
            request, template_name, {
                'info': info,
                'form': form,
                'user': request.user,
                'city_message': city_message,
                'warning_message': warning_message,
            })
        return result
Exemple #5
0
def index():
    # Стартовая страница
    if request.method == 'POST':
        city_name = request.form['city'].capitalize(
        )  # Установка заглавной буквы
        if City.city_in_db(city_name):  # Проверка наличия города в базе
            flash('{} is already in the database!'.format(city_name), 'danger')
            return redirect(url_for('main.index'))

        if weather_request(
                city_name
        )['cod'] == '404':  # Проверка наличия города в базе OpenWeatherMap
            flash('{} does not exist!'.format(city_name), 'danger')
            return redirect(url_for('index'))

        date_added = datetime.datetime.now().strftime(
            '%d. %b %Y, %H:%M')  # Установка текущей даты
        city_object = City(name=city_name, date_added=date_added)
        db.session.add(city_object)
        flash('{} has been successfully added'.format(city_name), 'success')
        current_app.logger.info('New record added')
        db.session.commit()
    if City:
        all_cities = City.query.order_by(
            City.date_added.desc()).all()  # Все записи БД

    weather_data = []

    for city in all_cities:  # Формирование словаря со всеми записями для отображения на странице
        req = weather_request(city.name)
        weather = {
            'city': req['name'],
            'id': city.id,
            'temperature': req['main']['temp'],
            'feels_like': req['main']['feels_like'],
            'description': req['weather'][0]['description'],
            'icon': req['weather'][0]['icon'],
            'date_added': city.date_added
        }

        weather_data.append(weather)
    return render_template('index.html', weather_data=weather_data)
Exemple #6
0
    def get(self, request):
        city_name = request.GET.get('city_name', None)
        country_code = request.GET.get('code', None)
        if not city_name:
            return Response({'message': "You should enter city_name!"},
                            status.HTTP_400_BAD_REQUEST)
        try:
            profile = Profile.objects.get(user=request.user)
        except Profile.DoesNotExist:
            return Response({'message': "Profile does not exist"},
                            status=status.HTTP_400_BAD_REQUEST)

        app_id = '&units=metric&appid=d5690ce2c8cf4f332eb7788636e9bc69'
        if country_code:
            app_id = ',' + country_code + app_id
        url = 'https://api.openweathermap.org/data/2.5/weather?q={}' + app_id
        response = requests.get(url.format(city_name)).json()
        if response['cod'] == '404':  # Request error
            return Response({'message': "The city wasn't found!"},
                            status.HTTP_404_NOT_FOUND)
        if country_code:
            if profile.cities.filter(city_name=city_name,
                                     country_code=country_code):
                return Response({'message': "City already in list!"},
                                status.HTTP_400_BAD_REQUEST)
        else:
            if profile.cities.filter(city_name=city_name):
                return Response({'message': "City already in list!"},
                                status.HTTP_400_BAD_REQUEST)
        weather = Weather()
        weather.save(response=response)
        country_code = response['sys']['country']
        city = City(profile=profile,
                    city_name=city_name,
                    country_code=country_code,
                    weather=weather)
        city.save()

        return Response({'message': "Successfully added"},
                        status.HTTP_201_CREATED)
Exemple #7
0
def search_city(request):
    url_api = 'http://api.openweathermap.org/data/2.5/forecast?q={}&appid=24fa72dcfd34b9a33c1b1c518534a45b'
    city_name = request.POST.get('pretraga')
    if len(city_name) == 0:
        apps.get_app_config('weather_app').message = 'City not found!'
        apps.get_app_config('weather_app').error = True
        return redirect('base')
    r = requests.get(url_api.format(city_name)).json()
    if r['cod'] == '404':
        apps.get_app_config('weather_app').message = 'City not found!'
        apps.get_app_config('weather_app').error = True
        return redirect('base')
    else:
        dict_of_dates = format_api_response(r)
        if len(apps.get_app_config('weather_app').list_of_dates) > 0:
            pass
        else:
            for date in dict_of_dates:
                apps.get_app_config('weather_app').list_of_dates.append(date)
        stats = None
        for stat in dict_of_dates:
            for s in dict_of_dates[stat]:
                stats = dict_of_dates[stat][s]
                break
            break
        city = City(city_name, dict_of_dates, stats)
        graph = initialize_graph_data(city)
        city.graph = graph
        if city in apps.get_app_config('weather_app').list_of_cities:
            apps.get_app_config('weather_app').message = 'City already added!'
            apps.get_app_config('weather_app').error = True
            return redirect('base')
        else:
            if len(apps.get_app_config('weather_app').list_of_cities) < 4:
                apps.get_app_config('weather_app').list_of_cities.append(city)
                apps.get_app_config('weather_app').error = False
        return redirect('base')
Exemple #8
0
 def test_default_cities(self):
     city = City()
     self.assertEqual(city.name, '')
Exemple #9
0
    def test_save_and_retrieve_cities(self):
        list_ = List()
        list_.save()

        first_city = City()
        first_city.name = 'First city'
        first_city.list = list_
        first_city.save()

        second_city = City()
        second_city.name = 'Second city'
        second_city.list = list_
        second_city.save()

        saved_list = List.objects.first()
        self.assertEqual(saved_list, list_)

        saved_cities = City.objects.all()
        self.assertEqual(saved_cities.count(), 2)

        first_saved_city = saved_cities[0]
        second_saved_city = saved_cities[1]
        self.assertEqual(first_saved_city.name, 'First city')
        self.assertEqual(first_saved_city.list, list_)
        self.assertEqual(second_saved_city.name, 'Second city')
        self.assertEqual(second_saved_city.list, list_)
Exemple #10
0
 def test_can_save_the_same_city_to_different_list(self):
     list_first = List.objects.create()
     list_second = List.objects.create()
     City.objects.create(name='City', list=list_first)
     city = City(name='City', list=list_second)
     city.full_clean()