Пример #1
0
def index():
    data = getWeather()
    form = CityForm()
    if form.validate_on_submit():
        data = getWeatherCity(form.city_name.data)
        return render_template('index.html', data=data, form=form)
    return render_template('index.html', data=data, form=form)
Пример #2
0
def city_form_post(
        request):  # обработка POST запроса из формы добавления города
    raw_data = CityForm(request.POST)
    if raw_data.is_valid():
        data = raw_data.cleaned_data

        cities_in_db = Cities.objects.filter().values_list(
        )  # получаем список кортежей values городов из бащы
        cities_in_db_list = []  # создание пустого списка названий городов
        for item in cities_in_db:  # обходим все кортежи в списке
            cities_in_db_list.append(
                item[1]
            )  # нас интересует только второй элемент в кортеже (который name), добавляем его в список

        # проверка есть ли полученный город из формы списке названий городов, которые уже есть в базе
        if data['name'] in cities_in_db_list:  # если есть - возвращаем страницу с соответствующим сообщением
            context = {'city': data['name']}
            return render(request, 'result_page_city_fail.html', context)
        else:  # если нет - добавляем новый город в базу и выводим отчет
            city = Cities.objects.create(**data)
            context = {'city': city}
            return render(request, 'result_page_city.html', context)

    data = raw_data.errors
    return HttpResponse('{0}'.format(data))
Пример #3
0
def welcome():
    form = CityForm()
    if form.validate_on_submit():
        obj = ResultMaker()
        result = obj.call(form.city.data)
        if result == "not_found":
            return redirect(url_for('wrong_name'))
        clothes = obj.clothes()
        if form.degrees.data == True:
            result['temperature'] -= 273
        return redirect(url_for('.information', clothes=clothes, city=result))
    return render_template("welcome.html", form=form)
Пример #4
0
def edit_city(id):
    '''
    Edit City
    '''
    city = City.query.filter_by(id=id).first()
    form = CityForm(obj=city)
    if form.validate_on_submit():
        try:
            form.populate_obj(city)
            db.session.add(city)
            db.session.commit()
            flash('Saved successfully', 'success')
        except:
            db.session.rollback()
            flash('Error updating city.', 'danger')
    return render_template('web/edit_city.html', form=form)
Пример #5
0
def create_city():
    '''
    Create city
    '''
    form = CityForm()
    if form.validate_on_submit():
        city = City()
        form.populate_obj(city)
        db.session.add(city)
        try:
            db.session.commit()
            flash('City created correctly', 'success')
            return redirect(url_for('city.cities', **request.args))
        except Exception as e:
            db.session.rollback()
            flash('Error creating city', 'danger')

    return render_template('web/create_city.html', form=form)
Пример #6
0
def city_form_post(request):  # обработка POST запроса из формы добавления города
    raw_data = CityForm(request.POST)
    if raw_data.is_valid():
        data = raw_data.cleaned_data

        cities_in_db = Cities.objects.filter().values_list()  # получаем список кортежей values городов из бащы
        cities_in_db_list = []  # создание пустого списка названий городов
        for item in cities_in_db:  # обходим все кортежи в списке
            cities_in_db_list.append(item[1])  # нас интересует только второй элемент в кортеже (который name), добавляем его в список

        # проверка есть ли полученный город из формы списке названий городов, которые уже есть в базе
        if data['name'] in cities_in_db_list:  # если есть - возвращаем страницу с соответствующим сообщением
            context = {'city': data['name']}
            return render(request, 'result_page_city_fail.html', context)
        else:  # если нет - добавляем новый город в базу и выводим отчет
            city = Cities.objects.create(**data)
            context = {'city': city}
            return render(request, 'result_page_city.html', context)

    data = raw_data.errors
    return HttpResponse('{0}'.format(data))
Пример #7
0
def index(request):
    src = ''
    dst = ''
    weather_url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=33815ab6524fca76a8bbe9a95df35754'
    
    cities = City.objects.all()        

    if request.method == 'POST':
        form = CityForm(request.POST)
        form.save()
    else:
        form = CityForm()
        
    weather_data = []

    for city in cities:
        city_weather = requests.get(weather_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)
        city.temp = weather['temperature']
        if city.option == '1':
            src = str(city.name)
        elif city.option == '2':
            dst = str(city.name)
            
        city.save()

    context = {'weather_data' : weather_data, 'form' : form, 'src' : src, 'dst' : dst}
    return render(request, 'weather/index.html', context)
Пример #8
0
def add():
    form = CityForm(request.form)
    con = sqlite3.connect("IK.db")
    con.row_factory = dict_factory
    cursor = con.cursor()
    if request.method == "POST":
        name  = form.name.data
        description = form.description.data
        sorgu = 'insert into  city   (name, description ) values (? , ? )'
        cursor.execute(sorgu, (name,description))
        con.commit()
        flash("Yeni kayıt Eklendi" ,"success")
        return redirect(url_for("list"))
    return render_template("cities/add.html" ,form = form)
Пример #9
0
def city_new(request):
    if request.method == "POST":
        form = CityForm(request.POST, request.FILES)
        if form.is_valid():
            city = form.save(commit=False)
            city.save()
            form.save_m2m()
            return redirect('website.views.city_detail', pk=city.pk)
    else:
        form = CityForm()
    return render(request, 'website/city_new.html', {'form': form})
Пример #10
0
def delete(id): 
    form = CityForm(request.form)   
    con = sqlite3.connect("IK.db")
    con.row_factory = dict_factory
    cursor = con.cursor()
    if request.method == "GET":
        sorgu = 'select * from city where id = ?'
        city = cursor.execute(sorgu,(id,)).fetchone()
        form.name.data = city["name"]
        form.description.data = city["description"]
        return render_template("cities/delete.html" ,form = form)
    else:
        sorgu = 'delete from city  where id = ?'
        cursor.execute(sorgu, (id,))
        con.commit()
        flash("Silme Başarılı " ,"success")
        return redirect(url_for("list"))
Пример #11
0
def city_edit(request, pk):
    city = get_object_or_404(City, pk=pk)
    if request.method == "POST":
        form = CityForm(request.POST, request.FILES, instance=city)
        if form.is_valid():
            city = form.save(commit=False)
            city.save()
            form.save_m2m()
            return redirect('website.views.city_detail', pk=city.pk)
    else:
        form = CityForm(instance=city)
    return render(request, 'website/city_new.html', {'form': form})
Пример #12
0
def index(request):
    url = '''http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=fd1ddc9ac4c6b84d80efc1908d3d0944'''
    cities = City.objects.all()  #return all the cities in the database

    if request.method == 'POST':  #only true if form is submitted
        form = CityForm(
            request.POST)  #add actual request data to form for processing

        if not City.objects.filter(name=form['name'].value()).exists() and (
                requests.get(url.format(form['name'].value())).status_code
                == 200):  #only saves if city is valid
            #and does not exist
            form.save()  # will validate and save if validate

    form = CityForm()

    weather_data = []

    for city in cities:

        city_weather = requests.get(url.format(city)).json(
        )  #request the API data and convert the JSON to Python data types

        weather = {
            'city': city,
            'temperature': round((city_weather['main']['temp'] - 32) * 5 / 9,
                                 1),  #covert Fahrenheit to Celsius
            'description': city_weather['weather'][0]['description'],
            'icon': city_weather['weather'][0]['icon']
        }

        weather_data.append(
            weather)  #add the data for the current city into our list

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

    return render(request, 'weather/index.html',
                  context)  #return index.html template
Пример #13
0
def about():
    city_form = CityForm(request.form)

    return render_template("about.html", city_form=city_form)
Пример #14
0
def home():
    city_form = CityForm(request.form)

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

        opwm_json_response = get(f"https://api.openweathermap.org/data/2.5/weather"
                                 f"?lat={location_lat}"
                                 f"&lon={location_lon}"
                                 f"&appid={OPWM_API_KEY}"
                                 f"&units=metric")\
                                     .json()

        opwm_uv_index_json_response = get(f"https://api.openweathermap.org/data/2.5/uvi"
                                          f"?&appid={OPWM_API_KEY}"
                                          f"&lat={location_lat}"
                                          f"&lon={location_lon}")\
                                              .json()

        opwm_forecast_json_response = get(f"https://api.openweathermap.org/data/2.5/forecast"
                                          f"?lat={location_lat}"
                                          f"&lon={location_lon}"
                                          f"&appid={OPWM_API_KEY}"
                                          f"&units=metric")\
                                              .json()

        timezonedb_json_response = get(f"http://api.timezonedb.com/v2.1/get-time-zone"
                                       f"?format=json"
                                       f"&by=position"
                                       f"&lat={location_lat}"
                                       f"&lng={location_lon}"
                                       f"&key={TIMEZONEDB_API_KEY}")\
                                           .json()

        aq_json_response = get(f"http://api.airvisual.com/v2/nearest_city"
                               f"?lat={location_lat}"
                               f"&lon={location_lon}"
                               f"&key={AIRQUALITY_API_KEY}")\
                                   .json()

        try:
            cache.set("weather_wind_direction_deg",
                      round(opwm_json_response["wind"]["deg"]))
            cache.set("weather_wind_direction_abbr",
                      portolan.point(degree=cache.get("weather_wind_direction_deg"))\
                        .capitalize())
        except KeyError:
            cache.set("weather_wind_direction_deg", None)
            cache.set("weather_wind_direction_abbr", "No data")

        cache.set("user_query_location",
                  city_form.location.data.split(",")[0]\
                    .title())
        cache.set("country_code", opwm_json_response["sys"]["country"])
        cache.set("country_full_name",
                  countries.get(opwm_json_response["sys"]["country"]).name)
        cache.set("country_emoji_flag",
                  flag.flagize(f":{opwm_json_response['sys']['country']}:"))
        cache.set("location_station_name", opwm_json_response["name"])
        cache.set(
            "location_more_link", f"https://www.google.com/search"
            f"?q={cache.get('user_query_location')}")
        cache.set(
            "location_local_time",
            datetime.strptime(timezonedb_json_response["formatted"],
                              "%Y-%m-%d %H:%M:%S"))
        cache.set("weather_time_calc_utc",
                  datetime.fromtimestamp(opwm_json_response["dt"])\
                    .strftime("%d/%m/%Y, at %H:%M"))
        cache.set("weather_temp_current",
                  round(opwm_json_response["main"]["temp"], 1))
        cache.set("weather_temp_min",
                  round(opwm_json_response["main"]["temp_min"], 1))
        cache.set("weather_temp_max",
                  round(opwm_json_response["main"]["temp_max"], 1))
        cache.set("weather_description",
                  opwm_json_response["weather"][0]["description"]\
                    .capitalize())
        cache.set("weather_pressure", opwm_json_response["main"]["pressure"])
        cache.set("weather_humidity", opwm_json_response["main"]["humidity"])
        cache.set("weather_wind_speed", opwm_json_response["wind"]["speed"])
        cache.set("weather_uv_index",
                  round(opwm_uv_index_json_response["value"]))
        cache.set("weather_air_quality_index",
                  aq_json_response["data"]["current"]["pollution"]["aqius"])
        cache.set("weather_temp_forecast", [
            temp["main"]["temp"]
            for temp in opwm_forecast_json_response["list"][::5]
        ])
        cache.set("weather_forecast_time_calc_utc", [
            datetime.strptime(time_calc["dt_txt"], "%Y-%m-%d %H:%M:%S")
            for time_calc in opwm_forecast_json_response["list"][::5]
        ])

        city_form.location.data = ""

        return render_template("weather_report.html",
                               cache=cache,
                               city_form=city_form)

    return render_template("home.html", cache=cache, city_form=city_form)
Пример #15
0
def detailed_user_profile_form(request, id=None):
    init_data = {}
    user = request.user
    user_profile = UserProfile.objects.get(user_id=request.user.id)
    if request.method == 'POST':
        user_profile_form = DetailedUserProfileForm(request.POST, request.FILES)

        if user_profile_form.is_valid():
            # User info
            user.username = user_profile_form.cleaned_data['user_name']
            user.first_name = user_profile_form.cleaned_data['first_name']
            user.last_name = user_profile_form.cleaned_data['last_name']
            user.email = user_profile_form.cleaned_data['email']
            user.save(force_insert=False,
                      force_update=True,
                      update_fields=('username', 'first_name', 'last_name', 'email'))
            # Address : address and city
            city_data = {
                'name': user_profile_form.cleaned_data['city'],
                'zipcode': user_profile_form.cleaned_data['zipcode'],
                'country': user_profile_form.cleaned_data['country']
            }

            # Check if we can get this city
            # If the city doesn't exist, we try to create it, but data may be incomplete
            try:
                city = City.objects.get(**city_data)
            except ObjectDoesNotExist:
                try:
                    city = CityForm(data=city_data).save()
                except ValueError:
                    city = None

            if city is not None:
                address_data = {
                    'num': user_profile_form.cleaned_data['num'],
                    'street': user_profile_form.cleaned_data['street'],
                    'city': city.pk,
                }

                try:
                    address = Address.objects.get(**address_data)
                except ObjectDoesNotExist:
                    try:
                        address = AddressForm(data=address_data).save()
                    except ValueError:
                        address = None
            else:
                address = None

            user_profile.address = address
            user_profile.dialcode = user_profile_form.cleaned_data['dialcode']
            user_profile.phone_number = user_profile_form.cleaned_data['phone_number']
            user_profile.school = user_profile_form.cleaned_data['school']
            user_profile.studies_domain = user_profile_form.cleaned_data['studies_domain']

            # Profile picture
            if 'profile_picture' in user_profile_form.changed_data:
                import Image as Pil
                import StringIO, time
                from django.core.files.uploadedfile import InMemoryUploadedFile

                profile_pic = Pil.open(request.FILES.get('profile_picture'))
                profile_pic.thumbnail((200, 200), Pil.ANTIALIAS)
                ppic_io = StringIO.StringIO()
                profile_pic.save(ppic_io, request.FILES['profile_picture'].content_type.split('/')[-1].upper())
                ppic_filename = request.user.username + '_avatar_' + str(int(time.time()))
                ppic_file = InMemoryUploadedFile(ppic_io,
                                                 u"profile_picture",
                                                 ppic_filename,
                                                 request.FILES['profile_picture'].content_type,
                                                 ppic_io.len,
                                                 None)
                user_profile.profile_picture = ppic_file

            user_profile.save()

            return redirect(reverse('profiles-list'))

        else:
            return render(request,
                          'forms/detailed_userprofile_form.html',
                          {'form': user_profile_form})

    init_data = {
        'user_name': user.username,
        'first_name': user.first_name,
        'last_name': user.last_name,
        'email': user.email,
        'confirm_email': user.email
    }

    if user_profile.address is not None:
        user_address = Address.objects.get(pk=user_profile.address.pk)
        user_city = City.objects.get(pk=user_address.city.pk)
        init_data.update({
            'num': user_address.num,
            'street': user_address.street,
            'city': user_city.name,
            'zipcode': user_city.zipcode,
            'country': user_city.country,
            'phone_number': user_profile.phone_number,
            'school': user_profile.school,
            'studies_domain': user_profile.studies_domain,
        })
    if user_profile.dialcode is not None:
        init_data['dialcode'] = CallingCode.objects.get(pk=user_profile.dialcode.pk)

    if user_profile.profile_picture is not None:
        init_data['profile_picture'] = user_profile.profile_picture

    return render(request, 'forms/detailed_userprofile_form.html',
                  {'form': DetailedUserProfileForm(initial=init_data)})
Пример #16
0
def city_form(
        request):  # рендер страницы с POST запросом для добавления города
    context = {'city_form': CityForm()}
    return render(request, 'city_form.html', context)
Пример #17
0
def edit_fulladdress(request):
    print "edit full"
    user_profile = request.user.user_profile
    saved = False
    new_address_parts = {
        'city': False,
        'address': False
    }

    if request.method == 'POST':
        print "Request method is PPOST"
        form = FullAddressForm(request.POST)

        if form.is_valid():
            print "Form is valid"
            # Address : address and city
            city_data = {
                'name': form.cleaned_data['city'],
                'zipcode': form.cleaned_data['zipcode'],
                'country': form.cleaned_data['country']
            }

            # Check if we can get this city
            # If the city doesn't exist, we try to create it, but data may be incomplete
            try:
                city = City.objects.get(**city_data)
            except ObjectDoesNotExist:
                try:
                    city = CityForm(data=city_data).save()
                    if city is not None:
                        new_address_parts['city'] = True
                        new_address_parts['city_name'] = city.__str__()
                except ValueError:
                    city = None

            if city is not None:
                address_data = {
                    'num': form.cleaned_data['num'],
                    'street': form.cleaned_data['street'],
                    'city': city.pk,
                }

                try:
                    address = Address.objects.get(**address_data)
                except ObjectDoesNotExist:
                    try:
                        address = AddressForm(data=address_data).save()
                        print "SAVe address"
                        new_address_parts['address'] = True
                    except ValueError:
                        address = None
            else:
                address = None

            user_profile.address = address
            user_profile.save()
            saved = True

        else:
            return render(request, 'forms/self_edit/address.html',
                          {'form': form})

    init_data = {}

    if user_profile.address is not None:
        user_address = Address.objects.get(pk=user_profile.address.pk)
        user_city = City.objects.get(pk=user_address.city.pk)
        init_data.update({
            'num': user_address.num,
            'street': user_address.street,
            'city': user_city.name,
            'zipcode': user_city.zipcode,
            'country': user_city.country,
        })

        return render(request, 'forms/self_edit/address.html',
                      {
                          'form': FullAddressForm(initial=init_data),
                          'notice_saved': saved,
                          'new_address_parts': new_address_parts
                      })
    else:
        return render(request, 'forms/self_edit/address.html',
                      {
                          'form': FullAddressForm(),
                          'notice_saved': False
                      })
Пример #18
0
def not_found(e):
    city_form = CityForm(request.form)

    return render_template(
        "500.html", raw_user_query_location=city_form.location.data), 500
Пример #19
0
 def test_form(self):
     """testing if the form is valid"""
     form = CityForm(data=self.data_city)
     self.assertTrue(form.is_valid())