Python - Busco ayuda para hacer que el script funcione y descargue datos automáticamente

 
Vista:

Busco ayuda para hacer que el script funcione y descargue datos automáticamente

Publicado por ABR1 (1 intervención) el 18/08/2022 11:11:29
#!/usr/bin/env python
"""Provides data from the SkyGlow sensors of the EELabs project.
"""

import argparse
import re
import urllib
from datetime import datetime

import pandas as pd
import requests

__author__ = "Samuel Lemes-Perera"
__copyright__ = "Copyright 2021, EELabs"
__credits__ = ["Samuel Lemes-Perera"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Samuel Lemes-Perera"
__email__ = "[email protected]"
__status__ = "Production"


def datetime_valid(dt_str):
try:
datetime.fromisoformat(dt_str)
except:
return False
return True


# Load Params
parser = argparse.ArgumentParser()
parser.add_argument('--device', required=True, type=str, help='Unique device name')
parser.add_argument('--limit', type=int, help='Returns the first N points')
parser.add_argument('--f', '--from', help='Data from \'from\' date (ISO8601 format)')
parser.add_argument('--to', help='Data until \'to\' date (ISO8601 format)')
parser.add_argument('--interval',
help='Data from now to interval date. Interval structure: Int+Code: Date codes: (Y|M|W|D) and Time codes: (h|m|s). Cannot be used in conjunction with from or to params')
parser.add_argument('--output', help='Output filename')
args = parser.parse_args()

# Parse params
_device = args.device
_limit = args.limit
_from = args.f
_to = args.to
_interval = args.interval
_output = args.output

if _from is not None and _to is not None and _interval is not None:
print('Use \'from\' and/or \'to\' or \'interval\' but not together')
exit()

if _from is not None and not datetime_valid(_from):
print('From param is not valid ISO8601 format')
exit()

if _to is not None and not datetime_valid(_to):
print('To param is not valid ISO8601 format')
exit()

if _from is not None and _to is not None and datetime.fromisoformat(_from) > datetime.fromisoformat(_to):
print('To param is less than from param ')
exit()

if _interval is not None and not re.match("\d+(Y|M|W|D|h|m|s)", _interval):
print('Invalid interval format')
exit()

params = {k: v for k, v in {'limit': _limit, 'from': _from, 'to': _to, 'interval': _interval}.items() if v is not None}

if _output is None:
_output = '{}__{}___{}'.format(_device, "_".join("{}__{}".format(k.upper(), v) for k, v in params.items()),
datetime.now().isoformat())

# Generate url
hostname = 'https://data.eelabs.eu'
query = '/api/devices/{}/data?{}'.format(_device, urllib.parse.urlencode(params))

# Load data
final_df = None
while query is not None:
url = '{}{}'.format(hostname, query)
response = requests.get(url)
json_response = response.json()
query = json_response['next'] if 'next' in json_response else None

if 'data' in json_response['result']:
df = pd.DataFrame.from_records(json_response['result']['data'], columns=json_response['result']['columns'])
if final_df is None:
final_df = df
else:
final_df = pd.concat([final_df, df])
# print(json_response['result'])

if final_df is not None:
final_df.to_csv("{}.csv".format(_output))
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 2.808
Oro
Ha mantenido su posición en Python (en relación al último mes)
Gráfica de Python

Busco ayuda para hacer que el script funcione y descargue datos automáticamente

Publicado por tincopasan (1082 intervenciones) el 18/08/2022 14:51:42
1)el editor tiene el tag </>Código es para que se respete la indentación del script
2)deberías aclarar que valores se supone deben tener los argumentos que le pasas al script
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar