本文整理汇总了Python中core.logger.Logger.error方法的典型用法代码示例。如果您正苦于以下问题:Python Logger.error方法的具体用法?Python Logger.error怎么用?Python Logger.error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类core.logger.Logger
的用法示例。
在下文中一共展示了Logger.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: find_messages
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def find_messages(cls, email):
"""
Obtiene la lista de mensajes recibidos en el buzón.
:param email: Buzón de correo.
:return: La lista de mensajes.
"""
from clients.gmail_api import GmailApiClient
from core.logger import Logger
try:
messages = []
resource = GmailApiClient(email).messages()
page_token = None
while True:
response = resource.list(
pageToken=page_token,
includeSpamTrash=False,
q="in:inbox is:unread"
)
if "messages" in response:
for message in response["messages"]:
if not any(x for x in messages if x["id"] == message["id"]):
messages.append(message)
if "nextPageToken" in response:
page_token = response["nextPageToken"]
else:
break
except Exception as e:
Logger.error(e)
raise e
return messages
示例2: authorize
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def authorize(self, email):
"""
Establece el buzón receptor dado como autorizado, crea las etiquetas DUPLICADO,
GESTIONADO, PDTE REINTENTAR y ERROR en el buzón dado.
:param email: Identificador del buzón.
:return: El buzón autorizado.
"""
from pending_authorization import PendingAuthorizationManager
from core.logger import Logger
try:
entity = self.get_by_email(email)
if entity is not None:
# Marcamos el buzón como autorizado.
entity.is_authorized = True
# Añadimos la información de tracking.
entity.updated_by = self._user
entity.put()
# Obtenemos el diccionario que representa el buzón actualizado.
entity = entity.to_dict()
# Eliminamos la autorización.
PendingAuthorizationManager.delete(entity["user_id"])
except Exception as e:
Logger.error(e)
raise e
return entity
示例3: create
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def create(email, group_id, mailbox_id):
"""
Crea la autorización pendiente para el buzón dado.
:param email: Usuario del buzón.
:param group_id: Identificador del grupo.
:param mailbox_id: Identificador del buzón.
:return: La autorización creada.
"""
from core.logger import Logger
try:
# Creamos la entidad.
entity = PendingAuthorizationDao(
id=str(email),
group_id=int(group_id),
mailbox_id=int(mailbox_id)
)
entity.put()
# Obtenemos el diccionario que representa la autorización creada.
entity = entity.to_dict()
except Exception as e:
Logger.error(e)
raise e
return entity
示例4: _post_message
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def _post_message(self, message):
"""
Send the given message to the Facebook Messenger platform.
:param message: The message to post.
:return: The Facebook Messenger response.
"""
from core.logger import Logger
from google.appengine.api import urlfetch
from json import dumps
try:
# Post the message to the Facebook Messenger platform.
r = urlfetch.fetch(
url=self._fb_messenger_api_url,
method=urlfetch.POST,
headers={"Content-Type": "application/json"},
payload=dumps(message)
)
# Parse the response.
response = r.content if r.status_code == 200 else None
Logger.info("Facebook response:\n%s" % response)
# In case of error.
except BaseException as e:
Logger.error(e)
response = None
# Return the parsed response.
return response
示例5: authorize
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def authorize(self, email):
"""
Autoriza el buzón de correo indicado.
:param email: Identificador de buzón de correo.
:return: El buzón de correo autorizado.
"""
from managers.pending_authorization import PendingAuthorizationManager
from core.logger import Logger
try:
entity = self.get_by_email(email)
if entity is not None:
Logger.info("It's authorized: {}".format(entity.is_authorized))
# Marcamos el buzón como autorizado.
entity.is_authorized = True
entity.updated_by = self._user
entity.put()
# Obtenemos el diccionario que representa el buzón actualizado.
entity = entity.to_dict()
# Eliminamos la autorización.
PendingAuthorizationManager.delete(entity["user_id"])
except Exception as e:
Logger.error(e)
raise e
return entity
示例6: authorize
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def authorize(self, email):
"""
Establece el buzón receptor dado como autorizado.
:param email: Identificador del buzón.
:return: El buzón autorizado.
"""
from pending_authorization import PendingAuthorizationManager
from core.logger import Logger
try:
entity = self.get_by_email(email)
if entity is not None:
# Marcamos el buzón como autorizado.
entity.is_authorized = True
# Añadimos la información de tracking.
entity.updated_by = self._user
entity.put()
# Eliminamos la autorización.
PendingAuthorizationManager.delete(entity.email)
except Exception as e:
Logger.error(e)
raise e
return entity.to_dict()
示例7: get_raw_message
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def get_raw_message(self):
"""
Obtiene el bruto del mensaje correspondiente a los datos almacenados en la instancia actual.
:return: Una cadena de texto con el bruto del mensaje.
"""
try:
message = self.__create_message().as_string()
raw = base64.urlsafe_b64encode(message)
except Exception as e:
Logger.error(e)
raise e
return raw
示例8: create_label
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def create_label(self, label):
"""
Crea una nueva etiqueta, estableciendo el buzón de correo indicado como padre.
:param label: Etiqueta.
:return: La etiqueta creada.
"""
from clients.gmail_api import GmailApiClient
from core.logger import Logger
from models.label import LabelDao
try:
# Comprobamos que los datos obligatorios vengan informados.
if label.gmail_name is None:
raise Exception("Label gmail_name cannot be empty.")
# Establecemos el nombre de la etiqueta.
gmail_name = label.gmail_name
entity = self.get()
# Obtenemos el acceso al recurso 'labels' de Gmail API.
resource = GmailApiClient(entity.email).labels()
# Obtenemos todas las etiquetas del buzón para, en caso de
# existir ya, seleccionar dicha etiqueta en vez de crearla.
mailbox_labels = resource.list()
# Comprobamos si ya existe una etiqueta con el nombre propuesto.
current_label = next((l for l in mailbox_labels["labels"] if l["name"].lower() == gmail_name.lower()), None)
Logger.info("Current label: %s ", current_label)
# Si no existe la creamos.
if current_label is None:
response = resource.create(body={
"name": gmail_name,
"labelListVisibility": "labelShow",
"messageListVisibility": "show"
})
entity.updated_by = self._user
# Añadimos el identificador obtenido.
label_dao = LabelDao(**{"gmail_name": gmail_name, "gmail_id": response["id"]})
entity.labels.append(label_dao)
Logger.info("Created label: {}".format(label_dao.to_dict()))
else:
raise Exception("This label is already in this account.")
# manager.add_label(entity.gmail_id)
entity.put()
except Exception as e:
Logger.error(e)
raise e
return entity
示例9: delete
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def delete(email):
"""
Elimina la autorización pendiente correspondiente al buzón dado.
:param email: Usuario del buzón.
"""
from core.logger import Logger
try:
entity = Key(PendingAuthorizationDao, str(email)).get()
if entity is not None:
entity.key.delete()
except Exception as e:
Logger.error(e)
raise e
示例10: post
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def post(self):
"""
Obtiene los mensajes del buzón correspondiente al día recién cerrado.
"""
from core.logger import Logger
from json import loads
from clients.gmail_api import GmailApiClient
try:
# Obtenemos los datos de la petición.
sender = loads(self.request.get("sender_account"))
recipients = loads(self.request.get("recipient_accounts"))
# Obtenemos los mensajes de la cuenta emisora.
messages = self.find_messages(sender["email"])
resource = GmailApiClient(sender["email"]).messages()
if messages:
# Por cada mensaje encontrado.
for message in messages:
# Creamos un mensaje.
mssg = GmailApiClient.Message(resource.get(id=message["id"]))
# Creamos un mensaje para mappear el mensaje obtenido.
mssg2 = GmailApiClient.MessageMapper()
Logger.info(u"From address: {}".format(mssg.get_from()))
Logger.info(u"Sender address: {}".format(mssg.get_sender()))
# Seteamos los campos que nos interesan.
mssg2.set_html_body(mssg.get_html_body())
mssg2.set_subject(mssg.get_from() + "$ " + mssg.get_subject())
mssg2.add_header("Return-Path", u"{}".format(mssg.get_from()))
mssg2.add_header("X-Env-Sender", u"{}".format(mssg.get_from()))
mssg2.from_address = u"{}".format(mssg.get_from())
Logger.info(u"New from: {}".format(mssg2.from_address))
# Agregamos los buzones receptores.
for recipient in recipients:
mssg2.add_recipient(recipient["email"])
sender_email = sender["email"]
response = GmailApiClient(sender_email).send_message(mssg2, sender_email)
# Si obtenemos respuesta, borramos los mensajes del buzón emisor.
if response:
GmailApiClient(sender_email).messages().delete(
id=message["id"],
userId=sender_email
)
except Exception as e:
Logger.error(e)
示例11: send_message
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def send_message(self, message, user):
"""
Envía el mensaje dado.
"""
try:
# Si el mensaje no viene dado como corresponde.
if not isinstance(message, GmailApiClient.MessageMapper):
raise TypeError("The given message is not an instance of Message class.")
Logger.info("Sending the message...")
Logger.info("Message: {}".format(message))
# Obtenemos el mensaje en bruto y lo enviamos.
response = self.messages().send(
userId=user,
body={"raw": message.get_raw_message()}
)
except (errors.HttpError, TypeError), e:
Logger.error(e)
raise e
示例12: do_request
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def do_request(**kwargs):
"""
Realiza una petición a un recurso de Gmail API.
:param kwargs: Parámetros de la petición.
:type kwargs: dict.
:return: Respuesta de Gmail API.
"""
"""
Puede que ocurra un error de rateLimitExceeded o userRateLimitExceeded.
En ese caso la documentación oficial recomienda implementar un exponential backoff
https://developers.google.com/gmail/api/guides/migrate-from-emapi
https://developers.google.com/drive/v2/web/handle-errors
https://github.com/google/google-api-python-client/blob/master/googleapiclient/http.py#L65
"""
from core.logger import Logger
if "userId" not in kwargs:
kwargs["userId"] = "me"
Logger.info("Executing request...")
# Reintentamos 3 veces.
for n in range(0, 3):
try:
Logger.info("Try #{}".format(n + 1))
response = method(**kwargs).execute(num_retries=3)
return response
except errors.HttpError, e:
Logger.info(e)
Logger.info("Execution failed...")
Logger.info("Status: {}".format(e.resp.status))
Logger.info("Reason: {}".format(e.resp.reason))
if e.resp.status in [403, 429, 503] or \
e.resp.reason in ["rateLimitExceeded", "userRateLimitExceeded"]:
Logger.warning("Error {}. Retrying".format(e.resp.status))
time.sleep((2 ** n) + random.randint(0, 1000) / 1000)
else:
Logger.error("Unknown error: {}".format(e))
raise e
示例13:
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
# Wait for lock
self.lock.acquire()
# Ensure task hasn't already been started
if self.started:
self.lock.release()
return
self.started = True
try:
# Call task
self.result = self.target(*self.args, **self.kwargs)
except CancelException, e:
self.exception = sys.exc_info()
log.debug('Task cancelled')
except trakt.RequestError, e:
self.exception = sys.exc_info()
log.warn('trakt.tv request failed: %s', e)
except Exception, ex:
self.exception = sys.exc_info()
log.error('Exception raised in triggered function %r: %s', self.name, ex, exc_info=True)
finally:
# Release lock
self.complete = True
self.lock.release()
示例14: format
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
# TODO switch to a streamed format (to avoid the MemoryError)
def save(self, group, data, source=None):
name = '%s.%s' % (group, self.key)
if source:
name += '.%s' % source
# Build `directory`
directory = os.path.join(Environment.path.plugin_data, 'Artifacts')
# Ensure `directory` exists
try:
os.makedirs(directory)
except Exception, ex:
# Directory already exists
pass
# Build `path`
path = os.path.join(directory, '%s.json' % name)
try:
log.debug('Saving artifacts to %r', path)
# Dump `data` to file as JSON
json_write(path, ArtifactTransformer(data), cls=ArtifactEncoder)
except MemoryError, ex:
log.error('Unable to save artifacts: %s', ex, exc_info=True)
except OSError, ex:
log.error('Unable to save artifacts: %s', ex, exc_info=True)
示例15: __create_message
# 需要导入模块: from core.logger import Logger [as 别名]
# 或者: from core.logger.Logger import error [as 别名]
def __create_message(self):
"""
Construye un mensaje -email- con los datos almacenados en la instancia actual.
:return: El mensaje como MIMEText o MIMEMultipart.
"""
try:
Logger.info("Generating the message...")
# Si se han indicado cuerpos tanto en texto plano como en HTML.
if self.plain_body is not None and self.html_body is not None:
message = MIMEMultipart("alternative")
message.attach(MIMEText(self.plain_body, "plain"))
message.attach(MIMEText(self.html_body, "html"))
# Si solo se ha indicado el cuerpo en texto plano.
elif self.plain_body is not None:
message = MIMEText(self.plain_body, "plain")
# Si solo se ha indicado el cuerpo en HTML.
else:
message = MIMEText(self.html_body, "html")
Logger.info("Appending the attachments...")
# Si existen adjuntos.
if len(self.attachments) > 0:
# El mensaje pasa a ser un MIMEMultipart con los cuerpos adjuntos.
aux = message
message = MIMEMultipart()
message.attach(aux)
# Por cada adjunto.
for filename, content in self.attachments:
# Obtenemos su mimetype.
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype is None or encoding is not None:
mimetype = "application/octet-stream"
maintype, subtype = mimetype.split("/", 1)
# Construimos el part correspondiente al adjunto en base al mimetype.
if maintype == "text":
part = MIMEText(content, _subtype=subtype)
elif maintype == "image":
part = MIMEImage(content, _subtype=subtype)
elif maintype == "audio":
part = MIMEAudio(content, _subtype=subtype)
else:
part = MIMEBase(maintype, subtype)
part.set_payload(content)
part.add_header("Content-Disposition", "attachment", filename=filename)
# Añadimos el part del adjunto al principal.
message.attach(part)
Logger.info("Appending the headers...")
# Añadimos las cabeceras comunes.
message["Subject"] = self.subject
message["From"] = self.from_address
message["To"] = ", ".join([r[0] if r[1] is None else "%s <%s>" % r for r in self.to_recipients])
message["Cc"] = ", ".join([r[0] if r[1] is None else "%s <%s>" % r for r in self.cc_recipients])
message["Bcc"] = ", ".join([r[0] if r[1] is None else "%s <%s>" % r for r in self.bcc_recipients])
Logger.info(u"Final from:{}".format(message["From"]))
# Si existen otras cabeceras.
if len(self.headers) > 0:
# Las añadimos al part principal.
for key, value in self.headers:
message[key] = value
Logger.info("Message generated successfully")
Logger.info("The message: {}".format(message))
except Exception as e:
Logger.error(e)
raise e
return message