0

我正在尝试构建一些 lambda 函数,第一个是使用sib-api-v3-sdk通过 SendinBlue 发送电子邮件,另一个是使用investpy从 Investing 获取历史 etf 数据。

好吧,我的两个功能都有问题,没用...我尝试将时间更改为 10 分钟或更长时间,但什么也没发生,总是一样...

SendinBlue 函数显示了这一点:

    Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f151ca80100>: Failed to establish a new connection: [Errno 110] Connection timed out')': /v3/emailCampaigns

Investpy 函数显示了这一点:

ConnectionError: HTTPSConnectionPool(host='www.investing.com', port=443): Max retries exceeded with url: /instruments/HistoricalDataAjax (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f21949626a0>: Failed to establish a new connection: [Errno 110] Connection timed out'))

两者在本地都可以正常工作。

功能:SendinBlue

import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException
import os
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    logger.info('## EMPEZAMOS')
    logger.info('# Configure API key authorization: api-key #')
    configuration = sib_api_v3_sdk.Configuration()
    configuration.api_key['api-key'] = 'MY-API-KEY'
    logger.info('# create an instance of the API class')
    api_instance = sib_api_v3_sdk.EmailCampaignsApi(sib_api_v3_sdk.ApiClient(configuration))
    list_id = my_list
    email_list = sib_api_v3_sdk.UpdateEmailCampaignRecipients(list_ids=[list_id])
    email_sender = sib_api_v3_sdk.CreateEmailCampaignSender(name='My_name', email='My_mail')
    email_campaigns_create = sib_api_v3_sdk.CreateEmailCampaign(sender=email_sender, subject='Prueba Lambda', reply_to='My_mail', name='Prueba AWS Lambda', html_content='Hola esto es una prueba desde Lambda', recipients=email_list)
    logger.info('## CREAR NUEVAS CAMPAÑAS ##')
    try:
        # Create an email campaign
        api_response = 
        api_instance.create_email_campaign(email_campaigns_create)
        print(api_response)
        logger.info('# CAMAPÑA CREADA')
    except ApiException as e:
        print("Exception when calling EmailCampaignsApi- 
        >create_email_campaign: %s\n" % e)
        logger.error("ERROR: PROBLEMA AL CREAR CAM")
        logger.error(e)
    return print(api_response)

投资

import investpy
import pymysql
from db_parametros import *
import pandas as pd
import time
import sys
import logging

start_time = time.time()

logger = logging.getLogger()
logger.setLevel(logging.INFO)

#Conectamos a BBDD
try:
    conn = pymysql.connect(host=host, user=user, passwd=password, db=bbdd, connect_timeout=60)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit()
def lambda_handler(event, context):
    with conn.cursor() as cur:
        #Sacamos la relacion de datos que necesitamos para hacer la llamada a Investing
        query = 'SELECT  a.id, a.nombre, a.ISIN, i.name, i.full_name, i.stock_exchange, i.country 
FROM Activos a LEFT JOIN Paises p ON a.pais=p.id LEFT JOIN Regiones r ON a.region=r.id LEFT JOIN TipoMercados m ON a.mercadoInvesting=m.id LEFT JOIN Investing i ON a.isin=i.isin AND i.stock_exchange=m.nombre ORDER BY a.id;'
    tabla = cur.execute(query)

    df = pd.read_sql_query(query, conn)
    #print(df)
    x= len(df)
    #print(x)
    y =0

    for x in range (0, len(df)):
        while y <= x:
            try:
                print('ETF nº: '+ str(x+1) + ' -- Se esta cargando: ' + str(df.at[x, 'nombre']))
                df_data = investpy.get_etf_historical_data(etf=df.at[x, 'name'],
                                            country=df.loc[x, 'country'],
                                            from_date='01/01/2000',
                                            to_date='01/01/2022')
                df_data = df_data.reset_index()
                df_data = df_data[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']]
                df_data['idActivo'] = x+1
                #print(df_data)
                if x ==0:
                    cur.execute('TRUNCATE TABLE CotizacionesActivos')
                    #con.execute('')
                    df_data.to_sql('CotizacionesActivos', conn, if_exists = 'append', index=False)
                else:
                    df_data.to_sql('CotizacionesActivos', conn, if_exists = 'append', index=False)
            except ValueError:
                print('ETF nº: '+ str(x+1) + ' -- **ERROR ** No se ha posido cargar: ' + str(df.at[x, 'nombre']))
                pass
            y += 1
        



    print("--- Completada carga en BBDD en %s minutos ---" % ((time.time() - start_time)/60))
return
4

0 回答 0