示例#1
0
 def test_error(self):
     logger = Logger(__name__)
     logger.error = mock.MagicMock()
     data = {'a': 'b'}
     logging.error(logger, 'hi', data)
     logger.error.assert_called_with(
         'hi\n%s',
         '\n`a`: b',
         exc_info=True,
         extra={'data': data},
     )
示例#2
0
文件: funcutil.py 项目: danqing/dqpy
 def decorated_func(*args, **kwargs):
     try:
         retval = func(*args, **kwargs)
         return True if noreturn else retval
     except Exception as e:
         error(
             logger, 'Error invoking {}'.format(func.__qualname__), {
                 'function': func.__qualname__,
                 'module': func.__module__,
                 'args': args,
                 'kwargs': kwargs,
                 'error': e,
             })
         return None
示例#3
0
def safe_fileinfo(path):
    """Retrive information of a file without throwing an error.

    If the path is invalid, None, 0, None will be returned.

    :param string path: The path to the file.
    :returns string mime: The MIME type of the file, such as text/plain.
    :returns int size: The size (in bytes) of the file.
    :returns string encoding: The encoding of the file, like gzip. This is
        suitable for use as the Content-Encoding header.
    """
    try:
        return fileinfo(path)
    except Exception as e:
        error(logger, 'Error getting fileinfo', {'path': path, 'error': e})
        return None, 0, None
示例#4
0
文件: redis.py 项目: danqing/dqpy
def init_redis(key):
    """Initialize a Redis connection.

    :param string key: The config key. The entry should at least contain the
        host, port and db number of the instance.
    :returns redis: The redis instance if the config exists and is valid, and
        None otherwise.
    """
    cfg = Config.get(key)
    if not cfg:
        return None
    try:
        i = redis.Redis(**cfg)
        # This will attempt to connect to Redis and throw an error if the
        # connection is invalid.
        i.info()
        return i
    except Exception:
        error(logger, 'Unable to connect to Redis', None)
        return None
示例#5
0
文件: database.py 项目: danqing/dqpy
def save_to_database(model, session=None):
    """Write things to the database.

    This function simply calls ``unsafe_save_to_database`` under the hood, but
    wraps the error into a ``ModelError`` upon failure.

    :param object/list model: The model object(s) to save. If a list is
        provided, the elements will be added one by one. Otherwise the object
        is added as-is.
    :param Session session: The optional database session to use.
    :raises ModelError: if the save fails.
    """
    try:
        unsafe_save_to_database(model, session=session)
    except Exception as e:
        error(logger, 'Error saving to database', {
            'model': model,
            'error': e,
        })
        raise ModelError(e.message if hasattr(e, 'message') else str(e))
示例#6
0
文件: email.py 项目: danqing/dqpy
def send_email(to, subject, html, sender_name, sender_email):
    """Send an email.

    :param string to: The recepient of the email.
    :param string subject: The subject of the email.
    :param string html: The HTML content of the email.
    :param string sender_name: The name of the sender.
    :param string sender_email: The sender address of the email.
    :returns boolean: True if the email is sent successfully. False otherwise.
    """
    mail = emails.Message(
        html=html,
        subject=subject,
        mail_from=(sender_name, sender_email),
    )
    resp = mail.send(to=to, smtp=SMTP_CONFIG)
    if not resp.success:
        error(logger, 'Failed to send email', {
            'error': resp.error.strerror,
            'to': to,
            'subject': subject,
        })
    return resp.success
示例#7
0
 def test_error_no_payload(self):
     logger = Logger(__name__)
     logger.error = mock.MagicMock()
     logging.error(logger, 'hi')
     logger.error.assert_called_with('hi', exc_info=True)