models.py 1.89 KB
Newer Older
1
"""Models for the util app. """
2 3 4 5
import cStringIO
import gzip
import logging

6
from config_models.models import ConfigurationModel
7 8 9 10 11 12
from django.db import models
from django.utils.text import compress_string

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name


13 14 15 16 17 18 19 20 21
class RateLimitConfiguration(ConfigurationModel):
    """Configuration flag to enable/disable rate limiting.

    Applies to Django Rest Framework views.

    This is useful for disabling rate limiting for performance tests.
    When enabled, it will disable rate limiting on any view decorated
    with the `can_disable_rate_limit` class decorator.
    """
22 23
    class Meta(ConfigurationModel.Meta):
        app_label = "util"
24 25


26
def decompress_string(value):
27 28 29 30 31
    """
    Helper function to reverse CompressedTextField.get_prep_value.
    """

    try:
32
        val = value.encode('utf').decode('base64')
33 34 35 36 37 38
        zbuf = cStringIO.StringIO(val)
        zfile = gzip.GzipFile(fileobj=zbuf)
        ret = zfile.read()
        zfile.close()
    except Exception as e:
        logger.error('String decompression failed. There may be corrupted data in the database: %s', e)
39
        ret = value
40 41 42 43
    return ret


class CompressedTextField(models.TextField):
44 45 46 47
    """ TextField that transparently compresses data when saving to the database, and decompresses the data
    when retrieving it from the database. """

    __metaclass__ = models.SubfieldBase
48 49

    def get_prep_value(self, value):
50
        """ Compress the text data. """
51 52 53 54 55 56 57
        if value is not None:
            if isinstance(value, unicode):
                value = value.encode('utf8')
            value = compress_string(value)
            value = value.encode('base64').decode('utf8')
        return value

58 59 60 61 62 63
    def to_python(self, value):
        """ Decompresses the value from the database. """
        if isinstance(value, unicode):
            value = decompress_string(value)

        return value