Ejemplo n.º 1
0
def meteoroMesGet(path: str, year1: int, year2: int, estaciones: list,
                  name: str):
    """
    devuelve los datos meteorológicos mensuales de las estaciones en un rango
        de años. En cada llamada aemet solo permite descargar una estación por
        año
    Se hace una primera petición get en la función request_to_aemet con el
        argumento meteoro=False; esta función devuelve un fichero json con 4
        parámetros (estado, descripcion, datos y metadatos). Estado es un
        estándar de respuestas del servidor; descripción es la idem de estado;
        datos es la url para descargar los datos solicitados; y metadatos es
        la url con los metadatos. Si la respuesta tieneéxito se hace una
        segunda petición con request_to_aemet con el argumento meteoro=True
        y utilizando las url devueltas en la primera petición; si tiene éxito
        se graban los datos
    Esta función tiene la misma estructura que meteoroDiaGet; si haces algún
        cambio aquí quizás lo tengas que trasladar a meteoroDiaGet
    args:
        path. carpeta donde se grabarán los resultados
        year1, year2. Años inicial y final de la petición de datos mensuales
        estaciones. lista de strings con los códigos de estaciones cuyos datos
            se desean descargar
        name. nombre de la tarea
    """
    from os.path import isfile, join
    from aemetOpenDataTaskMonth import TaskMonth
    from aemetOD_constants import MSGCONTINUE, URLBASE, meteoro_mes_url, \
    FMETADATA_METEORO_MES, STOP_REQUESTS, ANOTHER_REQUEST, SUCCESS_REQUEST, \
    MAXREQUEST

    try:
        task = TaskMonth.getTask(path, [year1, year2], estaciones, name,
                                 'meteoros mensuales')
    except ValueError as err:
        logging.append(err)
        _ = input(MSGCONTINUE)
        return

    NYEARSTEP = 1  # aemet no admite otro valor
    url_template = URLBASE + meteoro_mes_url
    file_metadatos = join(path, FMETADATA_METEORO_MES)
    wstations = [
        estacion for estacion in estaciones
        if estacion not in task.downloadedStations
    ]
    nestaciones = len(wstations)
    if nestaciones == 0:
        logging.append('Las estaciones ya se han descargado previamente')
        return

    start_time = time()

    for i, estacion in enumerate(wstations):
        if estacion in task.downloadedStations:
            continue
        year = year1
        nerrors, ndatos, ntry = 0, 0, 0
        ne = i + 1
        print(f'{estacion} {ne:d}/{nestaciones:d}')
        while year <= year2:
            nameFile = f'{estacion}_{year:d}_m.json'
            if isfile(join(path, nameFile)):
                year = year + NYEARSTEP
                continue

            url1 = url_template.format(f'{year:d}', f'{year:d}', estacion)
            code, r = request_to_aemet(url1, f'{estacion} {year:d}', False)
            if code == STOP_REQUESTS:
                nerrors += 1
                break
            elif code == ANOTHER_REQUEST:
                year = year + NYEARSTEP
                continue

            try:
                url2 = r.json()['datos']
            except ValueError as er:
                ntry += 1
                if ntry <= MAXREQUEST:
                    continue
                else:
                    logging.append(f'{er}', toScreen=False)
                    year = year + NYEARSTEP
                    continue

            code, r2 = request_to_aemet(url2, f'{estacion} {year:d}', True)
            if code == STOP_REQUESTS:
                nerrors += 1
                break
            elif code == ANOTHER_REQUEST:
                year = year + NYEARSTEP
                continue

            dst = join(path, nameFile)
            try:
                with open(dst, 'wb') as f:
                    for chunk in r2.iter_content(chunk_size=128):
                        f.write(chunk)
                ndatos += 1
            except Exception as er:
                logging.append(f'{er}', toScreen=False)
                nerrors += 1
                year = year + NYEARSTEP
                continue

            if not isfile(file_metadatos):
                url2 = r.json()['metadatos']
                code, r3 = request_to_aemet(url2, 'metadatos mensuales', True)
                if code == SUCCESS_REQUEST:
                    try:
                        with open(file_metadatos, 'wb') as f:
                            for chunk in r3.iter_content(chunk_size=128):
                                f.write(chunk)
                    except Exception as er:
                        logging.append(f'{er}', toScreen=False)

            year = year + NYEARSTEP

        ellapsed_time(start_time, nestaciones, ne, ndatos)
        logging.dump()
        if nerrors == 0:
            task.appendDownloadedStation(estacion)
            task.write()

    task.statusGet()
    logging.append('Descarga meteoros mensuales finalizada')
    _ = input(MSGCONTINUE)
Ejemplo n.º 2
0
        now = datetime.now()

        startTime = time()

        b = BHIMES(project, et_proc)
        b.aquifer_upsert_from_file()  # controlled in xml
        b.outcrop_upsert_from_file()
        b.met_upsert_from_file01()
        b.swb01()

        if annual_graphs:
            b.save_annual_graphs()  # xy recharge, runoff & ret
            b.save_annual_data_graphs()  # xy p, tmax, tmin, tavg
            b.save_annual_eth_graphs()  # xy pet (hargreaves)

        xtime = time() - startTime
        print(f'El script tardó {xtime:0.1f} s')

    except ValueError:
        msg = traceback.format_exc()
        logging.append(f'ValueError exception\n{msg}')
    except ImportError:
        msg = traceback.format_exc()
        logging.append(f'ImportError exception\n{msg}')
    except Exception:
        msg = traceback.format_exc()
        logging.append(f'Exception\n{msg}')
    finally:
        logging.dump()
        print('\nFin')
Ejemplo n.º 3
0
def meteoroDiaGet(path: str, fecha1: date, fecha2: date, estaciones: list,
                  name: str):
    """
    devuelve los datos meteorológicos diarios de las estaciones en un rango
        de fechas. En cada llamada aemet solo permite descargar hasta 5 años
        por estación
    Esta función tiene la misma estructura que meteoroMesGet; si haces algún
        cambio aquí quizás lo tengas que trasladar a meteoroMesGet
    args:
        path. carpeta donde se grabarán los resultados
        fecha1, fecha2. Fechas inicial y final de la descarga
        estaciones. lista de strings con los códigos de estaciones cuyos datos
            se desean descargar
        name. nombre de la tarea
    """
    from dateutil.relativedelta import relativedelta
    from os.path import isfile, join
    from aemetOpenDataTask import Task
    from aemetOD_constants import MSGCONTINUE, URLBASE, meteoro_dia_url, \
    FMETADATA_METEORO_DIA, STOP_REQUESTS, ANOTHER_REQUEST, SUCCESS_REQUEST, \
    MAXREQUEST

    try:
        task = Task.getTask(path, [fecha1, fecha2], estaciones, name,
                            'meteoros diarios')
    except ValueError as err:
        logging.append(err)
        _ = input(MSGCONTINUE)
        return

    DAYSTEP = relativedelta(days=1)
    NYEARSTEP = 4  # aemet permite hasta 5 años por petición
    url_template = URLBASE + meteoro_dia_url
    file_metadatos = join(path, FMETADATA_METEORO_DIA)
    wstations = [
        estacion for estacion in estaciones
        if estacion not in task.downloadedStations
    ]
    nestaciones = len(wstations)
    if nestaciones == 0:
        logging.append('Las estaciones ya se han descargado previamente')
        return

    start_time = time()

    for i, estacion in enumerate(wstations):
        if estacion in task.downloadedStations:
            continue
        fecha = fecha1
        nerrors, ndatos, ntry = 0, 0, 0
        ne = i + 1
        print(f'{estacion} {ne:d}/{nestaciones:d}')
        while fecha <= fecha2:
            fecha1_request = fecha.strftime("%Y-%m-%d")
            fecha_last = fecha + relativedelta(years=NYEARSTEP)
            fecha2_request = fecha_last.strftime("%Y-%m-%d")
            nameFile = f'{estacion}_{fecha1_request}_{fecha2_request}_d.json'
            if isfile(join(path, nameFile)):
                fecha = fecha_last + DAYSTEP
                continue

            url1 = url_template.format(f'{fecha1_request}T00:00:00UTC',
                                       f'{fecha2_request}T00:00:00UTC',
                                       f'{estacion}')
            code, r = request_to_aemet(url1,
                                       f'{estacion} {fecha1_request} ' +\
                                       f'{fecha2_request}', False)
            if code == STOP_REQUESTS:
                nerrors += 1
                break
            elif code == ANOTHER_REQUEST:
                fecha = fecha_last + DAYSTEP
                continue

            try:
                url2 = r.json()['datos']
            except ValueError as er:
                ntry += 1
                if ntry <= MAXREQUEST:
                    continue
                else:
                    logging.append(f'{er}', toScreen=False)
                    fecha = fecha_last + DAYSTEP
                    continue

            code, r2 = request_to_aemet(url2, f'{estacion} {fecha1_request}' +\
                                        f'{fecha2_request}', True)
            if code == STOP_REQUESTS:
                nerrors += 1
                break
            elif code == ANOTHER_REQUEST:
                fecha = fecha_last + DAYSTEP
                continue

            dst = join(path, nameFile)
            try:
                with open(dst, 'wb') as f:
                    for chunk in r2.iter_content(chunk_size=128):
                        f.write(chunk)
                ndatos += 1
            except Exception as er:
                logging.append(f'{er}', toScreen=False)
                nerrors += 1
                fecha = fecha_last + DAYSTEP
                continue

            if not isfile(file_metadatos):
                url2 = r.json()['metadatos']
                code, r3 = request_to_aemet(url2, 'metadatos diarios', True)
                if code == SUCCESS_REQUEST:
                    try:
                        with open(file_metadatos, 'wb') as f:
                            for chunk in r3.iter_content(chunk_size=128):
                                f.write(chunk)
                    except Exception as er:
                        logging.append(f'{er}', toScreen=False)

            fecha = fecha_last + DAYSTEP

        ellapsed_time(start_time, nestaciones, ne, ndatos)
        logging.dump()
        if nerrors == 0:
            task.appendDownloadedStation(estacion)
            task.write()

    task.statusGet()
    logging.append('Descarga meteoros diarios finalizada')
    _ = input(MSGCONTINUE)