def post(self):
        # registro de header y body del request
        #logging.info(self.request.headers)
        #logging.info(self.request.body)
        # seteo de parametros recibidos
        empresa = self.request.get('empresa')
        rut_receptor = self.request.get('rut_receptor')
        rut_emisor = self.request.get('rut_emisor')
        tipo_envio = self.request.get('tipo_envio')
        tipo_dte = self.request.get('tipo_dte')
        numero_folio = self.request.get('numero_folio')
        resolucion_receptor = self.request.get('resolucion_receptor')
        resolucion_emisor = self.request.get('resolucion_emisor')
        monto = self.request.get('monto')
        fecha_emision = self.request.get('fecha_emision')
        fecha_recepcion = self.request.get('fecha_recepcion')
        estado_documento = self.request.get('estado_documento')
        tipo_operacion = self.request.get('tipo_operacion')
        tipo_receptor = self.request.get('tipo_receptor')
        nombre_cliente = self.request.get('nombre_cliente')
        correo = self.request.get('correo')
        asunto = self.request.get('asunto')
        html = self.request.get('html')
        # seteo de adjuntos si es que lo hubiera
        adjunto1 = self.request.POST.get('adjunto1', None)
        adjunto2 = self.request.POST.get('adjunto2', None)
        adjunto3 = self.request.POST.get('adjunto3', None)

        if (correo and asunto and html and numero_folio and tipo_dte):
            # Proceso de creación del objeto email
            my_email = EmailModel()
            email_result = my_email.search_email(correo, numero_folio, tipo_dte)
            if email_result == None:
                #try:
                my_email.nombre_cliente = nombre_cliente
                my_email.correo = correo
                my_email.asunto = asunto
                my_email.html = html
                my_email.tipo_dte = tipo_dte
                my_email.numero_folio = numero_folio
                if empresa:
                    my_email.empresa = empresa
                if rut_receptor:
                    my_email.rut_receptor = rut_receptor
                if rut_emisor:
                    my_email.rut_emisor = rut_emisor
                if tipo_envio:
                    my_email.tipo_envio = tipo_envio
                if resolucion_receptor:
                    my_email.resolucion_receptor = resolucion_receptor
                if resolucion_emisor:
                    my_email.resolucion_emisor = resolucion_emisor
                if monto:
                    try:
                        my_email.monto = int(monto, base=10)
                    except:
                        pass
                if fecha_emision and not None:
                    my_email.fecha_emision = datetime.datetime.fromtimestamp(float(fecha_emision))
                if fecha_recepcion and not None:
                    my_email.fecha_recepcion = datetime.datetime.fromtimestamp(float(fecha_recepcion))
                if estado_documento:
                    my_email.estado_documento = estado_documento
                if tipo_operacion:
                    my_email.tipo_operacion = tipo_operacion
                if tipo_receptor:
                    my_email.tipo_receptor = tipo_receptor
                # Evaluar adjuntos
                if not adjunto1 == None:
                    att = AttachModel(
                        nombre=adjunto1.filename, archivo=adjunto1.file.read()).put()
                    my_email.attachs.append(att)
                if not adjunto2 == None:
                    att = AttachModel(
                        nombre=adjunto2.filename, archivo=adjunto2.file.read()).put()
                    my_email.attachs.append(att)
                if not adjunto3 == None:
                    att = AttachModel(
                        nombre=adjunto3.filename, archivo=adjunto3.file.read()).put()
                    my_email.attachs.append(att)
                my_email.put()
                context = {
                    'correo': correo,
                    'numero_folio': numero_folio,
                    'tipo_dte': tipo_dte,
                }
                # Inicio taskqueue
                q = taskqueue.Queue('InputQueue')
                t = taskqueue.Task(url='/inputqueue', params=context)
                q.add(t)
                self.response.write({'message': 'success'})
                #except Exception, e:
                #    logging.error(e)
            else:
                logging.info('objeto ya existe')
            # fin todo
        else:
            self.response.write({'message': 'error fields'})
    def post(self):
        """ Metodo que recibe los eventos generados al intentar enviar correos a SendGrid
        Los eventos capturados son (procesado, enviado, abierto, descartado, rebotado) """
        # se captura y se parsea a json el body del request recibido por el
        # webhook
        request_body = json.loads(self.request.body)

        for body in request_body:
            """ Evaluar el tipo de evento ya que trae campos diferentes """
            logging.info(request_body)

            event = str(body['event'])
            correo = str(body['email'])
            numero_folio = str(body['numero_folio'])
            tipo_dte = str(body['tipo_dte'])

            logging.info(event)

            if event and correo and numero_folio and tipo_dte:

                if event == 'processed':
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        email_model.smtp_id = body['smtp-id']
                        email_model.processed_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.processed_event = event
                        email_model.processed_sg_event_id = body['sg_event_id']
                        email_model.processed_sg_message_id = body['sg_message_id']
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        e.smtp_id = body['smtp-id']
                        e.processed_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.processed_event = event
                        e.processed_sg_event_id = body['sg_event_id']
                        e.processed_sg_message_id = body['sg_message_id']
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()

                elif event == 'delivered':
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        email_model.smtp_id = body['smtp-id']
                        email_model.delivered_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.delivered_event = event
                        email_model.delivered_sg_event_id = body['sg_event_id']
                        email_model.delivered_sg_message_id = body['sg_message_id']
                        email_model.delivered_response = body['response']
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        e.smtp_id = body['smtp-id']
                        e.delivered_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.delivered_event = event
                        e.delivered_sg_event_id = body['sg_event_id']
                        e.delivered_sg_message_id = body['sg_message_id']
                        e.delivered_response = body['response']
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()

                elif event == 'open':
                    model = EmailModel()
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        if email_model.opened_first_date == None:
                            email_model.opened_first_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.opened_last_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.opened_event = event
                        email_model.opened_ip = body['ip']
                        email_model.opened_user_agent = body['useragent']
                        email_model.opened_sg_event_id = body['sg_event_id']
                        email_model.opened_sg_message_id = body['sg_message_id']
                        model.email_add_count(email_model)
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        if e.opened_first_date == None:
                            e.opened_first_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.opened_last_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.opened_event = event
                        e.opened_ip = body['ip']
                        e.opened_user_agent = body['useragent']
                        e.opened_sg_event_id = body['sg_event_id']
                        e.opened_sg_message_id = body['sg_message_id']
                        e.email_add_count(e)
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()

                elif event == 'dropped':
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        email_model.smtp_id = body['smtp-id']
                        email_model.dropped_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.dropped_sg_event_id = body['sg_event_id']
                        email_model.dropped_sg_message_id = body['sg_message_id']
                        email_model.dropped_reason = body['reason']
                        email_model.dropped_event = event
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        e.smtp_id = body['smtp-id']
                        e.dropped_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.dropped_sg_event_id = body['sg_event_id']
                        e.dropped_sg_message_id = body['sg_message_id']
                        e.dropped_reason = body['reason']
                        e.dropped_event = event
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()

                elif event == 'bounce':
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        email_model.bounce_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.bounce_event = event
                        email_model.bounce_sg_event_id = body['sg_event_id']
                        email_model.bounce_sg_message_id = body['sg_message_id']
                        email_model.bounce_reason = body['reason']
                        email_model.bounce_status = body['status']
                        email_model.bounce_type = body['type']
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        e.bounce_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.bounce_event = event
                        e.bounce_sg_event_id = body['sg_event_id']
                        e.bounce_sg_message_id = body['sg_message_id']
                        e.bounce_reason = str(body['reason']).decode("utf-8")
                        e.bounce_status = body['status']
                        e.bounce_type = body['type']
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()

                elif event == 'unsubscribe':
                    email_model = EmailModel.search_email(correo, numero_folio, tipo_dte)
                    if not email_model == None:
                        email_model.unsubscribe_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        email_model.unsubscribe_uid = body['uid']
                        email_model.unsubscribe_purchase = body['purchase']
                        email_model.unsubscribe_id = body['id']
                        email_model.unsubscribe_event = body['event']
                        email_model.correo = str(body['email'])
                        email_model.numero_folio = str(body['numero_folio'])
                        email_model.tipo_dte = str(body['tipo_dte'])
                        email_model.put()
                    else:
                        e = EmailModel()
                        e.unsubscribe_date = datetime.datetime.fromtimestamp(body['timestamp'])
                        e.unsubscribe_uid = body['uid']
                        e.unsubscribe_purchase = body['purchase']
                        e.unsubscribe_id = body['id']
                        e.unsubscribe_event = body['event']
                        e.correo = str(body['email'])
                        e.numero_folio = str(body['numero_folio'])
                        e.tipo_dte = str(body['tipo_dte'])
                        e.put()
            else:
                logging.info('body con campos vacios')