コード例 #1
0
ファイル: views.py プロジェクト: andralves717/edc_tp1
def current_weather(request):
    if 'char_field_with_list' in request.POST:
        location_str = request.POST['char_field_with_list']
        if location_str == "":
            messages.warning(request, 'Empty search! Default location shown')
            location_str = 'Aveiro'
        location_str, location_id = get_local_id(location_str)
    elif 'c_name' in request.POST:
        lcl_id = int(request.POST['local_id'])
        c_name = request.POST['c_name']
        c_date = request.POST['c_date']
        c_comment = request.POST['c_comment']
        comment.new_comment(lcl_id, c_name, c_comment, c_date)
        location_str, location_id = local_str(lcl_id)
    elif 'local' in request.POST:
        location_id = int(request.POST['local'])
        location_str, location_id = local_str(location_id)
    else:
        location_str = 'Aveiro'
        location_str, location_id = get_local_id(location_str)
    # create or open db
    database()

    root_current = basex_actions.current_weather(location_str)

    xslt_file = etree.parse(f"{edc_tp1.settings.XML_URL}weather.xsl")
    transform = etree.XSLT(xslt_file)
    html = transform(root_current)

    if not basex_actions.city_in_db(location_id):
        root_forecast = basex_actions.api_call(location_id, to_string=True)

        if "<?xml" in root_forecast:
            root_forecast = root_forecast[39:]

        query = f"""let $d := doc('FiveDayForecast')
                            return insert node {root_forecast} as last into $d/FiveDayForecast """

        query2 = session.query(query)
        query2.execute()

    comments = comment.comment(location_id)
    data_list = tuple(all_pt_cities)
    form = FormForm(datalist=data_list)

    date = str(datetime.today().date())

    context = {
        'title': f'Meteorologia - {datetime.now().day}/{datetime.now().month}',
        'year': datetime.now().year,
        'forms': form,
        'location': location_str,
        'location_id': location_id,
        'content': html,
        'comment': comments,
        'title': "Meteorologia | Tempo Atual",
        'date': date,
    }
    return render(request, 'index.html', context)
コード例 #2
0
def database(name: str = "FiveDayForecast"):
    """

    :param name: name of db
    :return: if db does not exist, create and fill it with cities' weather info
            else, open db
    """
    try:
        session.execute(f"open {name}")
    except IOError:
        session.execute(f"create db {name}")

        db_root = etree.Element(name)
        for city in cities.values():
            root = basex_actions.api_call(city)
            db_root.append(root)

        session.add(f"{name}.xml", etree.tostring(db_root).decode("utf-8"))
コード例 #3
0
def current_weather(request):
    if 'local' in request.POST:
        location_str = request.POST['local']
        if location_str == "":
            messages.warning(request, 'Empty search! Default location shown')
            location_str = 'Aveiro'
    else:
        location_str = 'Aveiro'
    location_str, location_id = get_local_id(location_str)
    # create or open db

    database()

    root_current = basex_actions.current_weather(location_str)

    xslt_file = etree.parse(f"{edc_tp1.settings.XML_URL}weather.xsl")
    transform = etree.XSLT(xslt_file)
    html = transform(root_current)

    if not basex_actions.city_in_db(location_id):
        root_forecast = basex_actions.api_call(location_id, to_string=True)

        if "<?xml" in root_forecast:
            root_forecast = root_forecast[39:]

        query = f"""let $d := doc('FiveDayForecast')
                            return insert node {root_forecast} as last into $d/FiveDayForecast """

        query2 = session.query(query)
        query2.execute()

    context = {
        'title': f'Meteorologia - {datetime.now().day}/{datetime.now().month}',
        'year': datetime.now().year,
        'location': location_str,
        'location_id': location_id,
        'content': html,
        'title': "Meteorologia | Tempo Atual"
    }
    return render(request, 'index.html', context)
コード例 #4
0
def forecast(request, local_id):
    now = datetime.now()  # Dia e Hora(com minutos, segundos, etc) atuais
    remove_min_sec = timedelta(minutes=now.minute,
                               seconds=now.second,
                               microseconds=now.microsecond)
    now -= remove_min_sec  # Dia e Hora(apenas hora) atuais
    hour_of_today = now.hour
    remove_hour = timedelta(hours=hour_of_today)
    submit_day = now - remove_hour  # Dia de hoje (sem horas)
    hour_of_today -= (hour_of_today % 3)  # Hora atual divisível por 3 anterior
    now = submit_day + timedelta(hours=hour_of_today)
    if 'inputDia' in request.POST and 'inputHora' in request.POST:
        dia = request.POST['inputDia']
        hora = request.POST['inputHora']

        if dia == "Amanhã":
            sum_day = 1
        elif dia == "Daqui a 2 dias":
            sum_day = 2
        elif dia == "Daqui a 3 dias":
            sum_day = 3
        elif dia == "Daqui a 4 dias":
            sum_day = 4
        elif dia == "Daqui a 5 dias":
            sum_day = 5
        else:
            sum_day = 0

        submit_day += timedelta(days=sum_day)

        if hora == "00:00 - 03:00":
            sum_hour = 0
        elif hora == "03:00 - 06:00":
            sum_hour = 3
        elif hora == "06:00 - 09:00":
            sum_hour = 6
        elif hora == "09:00 - 12:00":
            sum_hour = 9
        elif hora == "12:00 - 15:00":
            sum_hour = 12
        elif hora == "15:00 - 18:00":
            sum_hour = 15
        elif hora == "18:00 - 21:00":
            sum_hour = 18
        elif hora == "21:00 - 00:00":
            sum_hour = 21

        submit_day += timedelta(hours=sum_hour)

        difference_data = submit_day - now

        if difference_data.days >= 5 or difference_data.days < 0:
            messages.warning(request, 'Selecione apenas até 5 dias.')
            submit_day = now
    elif 'local' in request.POST:
        location_str = request.POST['local']
        if location_str == "":
            messages.warning(request, 'Empty search! Default location shown')
            submit_day = now
        else:
            location_str, location_id = get_local_id(location_str)

            if not basex_actions.city_in_db(location_id):
                root_forecast = basex_actions.api_call(location_id,
                                                       to_string=True)

                if "<?xml" in root_forecast:
                    root_forecast = root_forecast[39:]

                query = f"""let $d := doc('FiveDayForecast')
                                    return insert node {root_forecast} as last into $d/FiveDayForecast """

                query2 = session.query(query)
                query2.execute()

            return redirect(f'/forecast/{location_id}')

    else:
        submit_day = now

    location_str, location_id = local_str(local_id)

    # create or open db
    database()

    query = f"""for $a in collection('FiveDayForecast')//weatherdata 
                for $b in $a/forecast/time 
                    where $a/location/location/@geobaseid = {location_id} and $b/@from = "{submit_day.isoformat()}"
                    return $b"""
    query2 = session.query(query)
    xml_forecast = query2.execute()

    # If the database's doesn't yet have the forecast
    if xml_forecast == "":
        basex_actions.update_forecast(location_str, location_id)

    root_forecast = etree.XML(xml_forecast)

    xslt_file = etree.parse(f"{edc_tp1.settings.XML_URL}forecast.xsl")
    transform = etree.XSLT(xslt_file)
    html = transform(root_forecast)

    context = {
        'title':
        f'Meteorologia - {submit_day.day}/{submit_day.month} - {submit_day.hour}:00',
        'year': datetime.now().year,
        'location': f'{location_str}',
        'location_id': location_id,
        'temp_inicio': submit_day.hour,
        'temp_fim': submit_day.hour + 3,
        'temp_dia': submit_day.day,
        'content': html,
        'title': "Meteorologia | Previsão 5 dias"
    }

    return render(request, 'forecast.html', context)