def get_version(version=None):
    """Derives a PEP386-compliant version number from VERSION."""
    if version is None:
        version = VERSION
    assert len(version) == 5
    assert version[3] in ('alpha', 'beta', 'rc', 'final')

    # Now build the two parts of the version number:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}N - for alpha, beta and rc releases

    parts = 2 if version[2] == 0 else 3
    main = '.'.join(str(x) for x in version[:parts])

    sub = ''
    if version[3] == 'alpha' and version[4] == 0:
        # At the toplevel, this would cause an import loop.
        from django.utils.version import get_version
        svn_revision = get_version()[4:]
        if svn_revision != 'unknown':
            sub = '.dev%s' % svn_revision

    elif version[3] != 'final':
        mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return main + sub
Example #2
0
def replace_javascript():
    """Check if we need to strip out 'text/javascript' bits"""
    # This is a bit of a hack, but I don't have an elegant way
    # of dealing with the change between Django 3.0 and 3.1 here
    djversion = get_version_tuple(get_version())
    if djversion[0] > 3 or (djversion[0] == 3 and djversion[1] > 0):
        return True
    return False
Example #3
0
    def add_arguments(self, parser):
        parser.add_argument('--queue', '-q', dest='queue', default='default',
                            help='Specify the queue [default]')
        parser.add_argument('--timeout', '-t', type=int, dest='timeout',
                            help='A timeout in seconds')

        if LooseVersion(get_version()) >= LooseVersion('1.8'):
            parser.add_argument('args', nargs='+')
def get_postprocess_counter_of_adjustable_file():
    """
    Since Django 1.11, postprocess algorythm has been changed for css files
    is such a way that they are postprocessed twice.
    """
    if version.get_version() == '1.11':
        return 2
    return 1
Example #5
0
 def __getstate__(self):
     """
     Allows the QuerySet to be pickled.
     """
     # Force the cache to be fully populated.
     self._fetch_all()
     obj_dict = self.__dict__.copy()
     obj_dict[DJANGO_VERSION_PICKLE_KEY] = get_version()
     return obj_dict
def model__reduce__(self):
    if model_is_deferred(self):
        return original_model__reduce__(self)
    else:
        cls = self.__class__
        data = self.__dict__.copy()
        data[DJANGO_VERSION_PICKLE_KEY] = get_version()

        vector = map(data.pop, attnames(cls))
        return model_unpickle, (cls, vector), data
Example #7
0
    def get_redirect_url(self, kind):
        # Hacks to account for the history of Django.
        # Some 0.9x.y releases failed and were replaced by the next one.
        superseded_by = {
            '0.91.1': '0.91.2',
            '0.95.2': '0.95.3',
            '0.96.1': '0.96.2',
        }.get(self.version)
        # Early 1.x.y releases had a different directory tree.
        has_subdir = (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 1, 1)
        if self.version_tuple[:3] in has_subdir:
            directory = '%d.%d.%d' % self.version_tuple[:3]
        else:
            directory = '%d.%d' % self.version_tuple[:2]
        # Django gained PEP 386 numbering in 1.4b1.
        if self.version_tuple >= (1, 4, 0, 'beta', 0):
            actual_version = get_version(self.version_tuple)
        # Early 1.0.x tarballs were named inconsistently.
        else:
            actual_version = {
                '1.0-alpha-2': '1.0-alpha_2',
                '1.0-beta-1': '1.0-beta_1',
                '1.0-beta-2': '1.0-beta_2',
                '1.0.1-beta-1': '1.0.1_beta_1',
                '1.0.1': '1.0.1-final',
                '1.0.2': '1.0.2-final',
            }.get(self.version, self.version)

        if kind == 'tarball':
            if superseded_by:
                pattern = '/download/%(superseded_by)s/tarball/'
            else:
                pattern = '%(media)sreleases/%(directory)s/Django-%(version)s.tar.gz'

        elif kind == 'checksum':
            if self.version_tuple[:3] >= (1, 0, 4):
                pattern = '%(media)spgp/Django-%(version)s.checksum.txt'
            else:
                raise ValueError('No checksum for this version')

        elif kind == 'egg':
            if self.version_tuple[:3] in [(0, 90, 0), (0, 91, 0)]:
                pattern = '%(media)sreleases/%(version)s/Django-%(version)s-py2.4.egg'
            else:
                raise ValueError('No egg for this version')

        return pattern % {
            'media': settings.MEDIA_URL,
            'directory': directory,
            'version': actual_version,
            'superseded_by': superseded_by,
            'major': self.version_tuple[0],
            'minor': self.version_tuple[1],
        }
Example #8
0
    def get_redirect_url(self, kind):
        # Hacks to account for the history of Django.
        # Some 0.9x.y releases failed and were replaced by the next one.
        superseded_by = {
            '0.91.1': '0.91.2',
            '0.95.2': '0.95.3',
            '0.96.1': '0.96.2',
        }.get(self.version)
        # Early 1.x.y releases had a different directory tree.
        has_subdir = (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 1, 1)
        if self.version_tuple[:3] in has_subdir:
            directory = '%d.%d.%d' % self.version_tuple[:3]
        else:
            directory = '%d.%d' % self.version_tuple[:2]
        # Django gained PEP 386 numbering in 1.4b1.
        if self.version_tuple >= (1, 4, 0, 'beta', 0):
            actual_version = get_version(self.version_tuple)
        # Early 1.0.x tarballs were named inconsistently.
        else:
            actual_version = {
                '1.0-alpha-2': '1.0-alpha_2',
                '1.0-beta-1': '1.0-beta_1',
                '1.0-beta-2': '1.0-beta_2',
                '1.0.1-beta-1': '1.0.1_beta_1',
                '1.0.1': '1.0.1-final',
                '1.0.2': '1.0.2-final',
            }.get(self.version, self.version)

        if kind == 'tarball':
            if superseded_by:
                pattern = '/download/%(superseded_by)s/tarball/'
            else:
                pattern = '%(media)sreleases/%(directory)s/Django-%(version)s.tar.gz'

        elif kind == 'checksum':
            if self.version_tuple[:3] >= (1, 0, 4):
                pattern = '%(media)spgp/Django-%(version)s.checksum.txt'
            else:
                raise ValueError('No checksum for this version')

        elif kind == 'egg':
            if self.version_tuple[:3] in [(0, 90, 0), (0, 91, 0)]:
                pattern = '%(media)sreleases/%(version)s/Django-%(version)s-py2.4.egg'
            else:
                raise ValueError('No egg for this version')

        return pattern % {
            'media': settings.MEDIA_URL,
            'directory': directory,
            'version': actual_version,
            'superseded_by': superseded_by,
            'major': self.version_tuple[0],
            'minor': self.version_tuple[1],
        }
Example #9
0
    def add_arguments(self, parser):
        parser.add_argument('--pid', action='store', dest='pid',
                            default=None, help='PID file to write the scheduler`s pid into')
        parser.add_argument('--interval', '-i', type=int, dest='interval',
                            default=60, help="""How often the scheduler checks for new jobs to add to the
                            queue (in seconds).""")
        parser.add_argument('--queue', dest='queue', default='default',
                            help="Name of the queue used for scheduling.",)

        if LooseVersion(get_version()) >= LooseVersion('1.9'):
            parser.add_argument('args', nargs='*')
def get_save_calls_counter_in_postprocess_of_adjustable_file():
    """
    Since Django 1.11, postprocess algorythm has been changed for css files
    is such a way that they save is called 4 times total.
    It must be taken into consideration in unittests.
    Hopefully this will be removed at some point once Django introduces optimization
    of postprocess handler.
    """
    if version.get_version() == '1.11':
        return 4
    return 1
Example #11
0
 def test_unsupported_unpickle(self):
     """
     #21430 -- Verifies a warning is raised for querysets that are
     unpickled with a different Django version than the current
     """
     qs = Group.previous_django_version_objects.all()
     with warnings.catch_warnings(record=True) as recorded:
         pickle.loads(pickle.dumps(qs))
         msg = force_text(recorded.pop().message)
         self.assertEqual(
             msg, "Pickled queryset instance's Django version 1.0 does not "
             "match the current version %s." % get_version())
Example #12
0
 def test_unsupported_unpickle(self):
     """
     #21430 -- Verifies a warning is raised for querysets that are
     unpickled with a different Django version than the current
     """
     qs = Group.previous_django_version_objects.all()
     with warnings.catch_warnings(record=True) as recorded:
         pickle.loads(pickle.dumps(qs))
         msg = force_text(recorded.pop().message)
         self.assertEqual(msg,
             "Pickled queryset instance's Django version %s does not "
             "match the current version %s."
             % (str(float(get_major_version()) - 0.1), get_version()))
Example #13
0
    def add_arguments(self, parser):
        parser.add_argument('--worker-class',
                            action='store',
                            dest='worker_class',
                            help='RQ Worker class to use')
        parser.add_argument('--pid',
                            action='store',
                            dest='pid',
                            default=None,
                            help='PID file to write the worker`s pid into')
        parser.add_argument('--burst',
                            action='store_true',
                            dest='burst',
                            default=False,
                            help='Run worker in burst mode')
        parser.add_argument('--with-scheduler',
                            action='store_true',
                            dest='with_scheduler',
                            default=False,
                            help='Run worker with scheduler enabled')
        parser.add_argument('--name',
                            action='store',
                            dest='name',
                            default=None,
                            help='Name of the worker')
        parser.add_argument('--queue-class',
                            action='store',
                            dest='queue_class',
                            help='Queues class to use')
        parser.add_argument('--job-class',
                            action='store',
                            dest='job_class',
                            help='Jobs class to use')
        parser.add_argument('--worker-ttl',
                            action='store',
                            type=int,
                            dest='worker_ttl',
                            default=420,
                            help='Default worker timeout to be used')
        parser.add_argument('--sentry-dsn',
                            action='store',
                            default=None,
                            dest='sentry-dsn',
                            help='Report exceptions to this Sentry DSN')

        if LooseVersion(get_version()) >= LooseVersion('1.10'):
            parser.add_argument(
                'args',
                nargs='*',
                type=str,
                help='The queues to work on, separated by space')
Example #14
0
    def add_arguments(self, parser):
        parser.add_argument('--queue',
                            '-q',
                            dest='queue',
                            default='default',
                            help='Specify the queue [default]')
        parser.add_argument('--timeout',
                            '-t',
                            type='int',
                            dest='timeout',
                            help='A timeout in seconds')

        if LooseVersion(get_version()) >= LooseVersion('1.9'):
            parser.add_argument('args', nargs='*')
Example #15
0
    def get_redirect_url(self, kind):
        # Hacks to account for the history of Django.
        # Some 0.9x.y releases failed and were replaced by the next one.
        superseded_by = {"0.91.1": "0.91.2", "0.95.2": "0.95.3", "0.96.1": "0.96.2"}.get(self.version)
        # Early 1.x.y releases had a different directory tree.
        has_subdir = (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 0, 4), (1, 1, 1)
        if self.version_tuple[:3] in has_subdir:
            directory = "%d.%d.%d" % self.version_tuple[:3]
        else:
            directory = "%d.%d" % self.version_tuple[:2]
        # Django gained PEP 386 numbering in 1.4b1.
        if self.version_tuple >= (1, 4, 0, "beta", 0):
            actual_version = get_version(self.version_tuple)
        # Early 1.0.x tarballs were named inconsistently.
        else:
            actual_version = {
                "1.0-alpha-2": "1.0-alpha_2",
                "1.0-beta-1": "1.0-beta_1",
                "1.0-beta-2": "1.0-beta_2",
                "1.0.1-beta-1": "1.0.1_beta_1",
                "1.0.1": "1.0.1-final",
                "1.0.2": "1.0.2-final",
            }.get(self.version, self.version)

        if kind == "tarball":
            if superseded_by:
                pattern = "/download/%(superseded_by)s/tarball/"
            else:
                pattern = "%(media)sreleases/%(directory)s/Django-%(version)s.tar.gz"

        elif kind == "checksum":
            if self.version_tuple[:3] >= (1, 0, 4):
                pattern = "%(media)spgp/Django-%(version)s.checksum.txt"
            else:
                raise ValueError("No checksum for this version")

        elif kind == "egg":
            if self.version_tuple[:3] in [(0, 90, 0), (0, 91, 0)]:
                pattern = "%(media)sreleases/%(version)s/Django-%(version)s-py2.4.egg"
            else:
                raise ValueError("No egg for this version")

        return pattern % {
            "media": settings.MEDIA_URL,
            "directory": directory,
            "version": actual_version,
            "superseded_by": superseded_by,
            "major": self.version_tuple[0],
            "minor": self.version_tuple[1],
        }
Example #16
0
    def __setstate__(self, state):
        msg = None
        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
        if pickled_version:
            current_version = get_version()
            if current_version != pickled_version:
                msg = ("Pickled queryset instance's Django version %s does"
                    " not match the current version %s."
                    % (pickled_version, current_version))
        else:
            msg = "Pickled queryset instance's Django version is not specified."

        if msg:
            warnings.warn(msg, RuntimeWarning, stacklevel=2)

        self.__dict__.update(state)
Example #17
0
    def get_context_data(self, *args, **kwargs):
        context = super(Base_Mixin, self).get_context_data(**kwargs)
        try:
            # 网站标题等内容
            context['website_title'] = settings.WEBSITE_TITLE
            context['website_welcome'] = settings.WEBSITE_WELCOME
            context['django_version'] = get_version()
            user = self.request.user
            if user.is_authenticated():
                context[
                    'notification_count'] = user.to_user_notification_set.filter(
                        is_read=0).count()
        except Exception:
            logger.error(u'[BaseMixin]加载基本信息出错')

        return context
Example #18
0
    def __setstate__(self, state):  # same in QuerySet
        msg = None
        pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)
        if pickled_version:
            current_version = get_version()
            if current_version != pickled_version:
                msg = (
                    "Pickled MultiDBQuerySet instance's Django version %s does not "
                    "match the current version %s." %
                    (pickled_version, current_version))
        else:
            msg = "Pickled MultiDBQuerySet instance's Django version is not specified."

        if msg:
            warnings.warn(msg, RuntimeWarning, stacklevel=2)

        self.__dict__.update(state)
Example #19
0
 def add_arguments(self, parser):
     parser.add_argument('--worker-class', action='store', dest='worker_class',
                         default='rq.Worker', help='RQ Worker class to use')
     parser.add_argument('--pid', action='store', dest='pid',
                         default=None, help='PID file to write the worker`s pid into')
     parser.add_argument('--burst', action='store', dest='burst',
                         default=False, help='Run worker in burst mode')
     parser.add_argument('--name', action='store', dest='name',
                         default=None, help='Name of the worker')
     parser.add_argument('--queue-class', action='store', dest='queue_class',
                         default='django_rq.queues.DjangoRQ', help='Queues class to use')
     parser.add_argument('--worker-ttl', action='store', type=int,
                         dest='worker_ttl', default=420,
                         help='Default worker timeout to be used')
     if LooseVersion(get_version()) >= LooseVersion('1.9'):
         parser.add_argument('args', nargs='*', type=str,
                             help='The queues to work on, separated by space')
Example #20
0
    def test_unsupported_unpickle(self):
        """
        #21430 -- Verifies a warning is raised for models that are
        unpickled with a different Django version than the current
        """
        class DifferentDjangoVersion(models.Model):
            title = models.CharField(max_length=10)

            def __reduce__(self):
                reduce_list = super(DifferentDjangoVersion, self).__reduce__()
                data = reduce_list[-1]
                data[DJANGO_VERSION_PICKLE_KEY] = '1.0'
                return reduce_list

        p = DifferentDjangoVersion(title="FooBar")
        with warnings.catch_warnings(record=True) as recorded:
            pickle.loads(pickle.dumps(p))
            msg = force_text(recorded.pop().message)
            self.assertEqual(
                msg, "Pickled model instance's Django version 1.0 does not "
                "match the current version %s." % get_version())
Example #21
0
    def add_arguments(self, parser):
        parser.add_argument('--worker-class', action='store', dest='worker_class',
                            help='RQ Worker class to use')
        parser.add_argument('--pid', action='store', dest='pid',
                            default=None, help='PID file to write the worker`s pid into')
        parser.add_argument('--burst', action='store_true', dest='burst',
                            default=False, help='Run worker in burst mode')
        parser.add_argument('--name', action='store', dest='name',
                            default=None, help='Name of the worker')
        parser.add_argument('--queue-class', action='store', dest='queue_class',
                            help='Queues class to use')
        parser.add_argument('--job-class', action='store', dest='job_class',
                            help='Jobs class to use')
        parser.add_argument('--worker-ttl', action='store', type=int,
                            dest='worker_ttl', default=420,
                            help='Default worker timeout to be used')
        parser.add_argument('--sentry-dsn', action='store', default=None, dest='sentry-dsn',
                            help='Report exceptions to this Sentry DSN')

        if LooseVersion(get_version()) >= LooseVersion('1.10'):
            parser.add_argument('args', nargs='*', type=str,
                                help='The queues to work on, separated by space')
Example #22
0
    def test_unsupported_unpickle(self):
        """
        #21430 -- Verifies a warning is raised for models that are
        unpickled with a different Django version than the current
        """
        class DifferentDjangoVersion(models.Model):
            title = models.CharField(max_length=10)

            def __reduce__(self):
                reduce_list = super(DifferentDjangoVersion, self).__reduce__()
                data = reduce_list[-1]
                data[DJANGO_VERSION_PICKLE_KEY] = str(float(get_major_version()) - 0.1)
                return reduce_list

        p = DifferentDjangoVersion(title="FooBar")
        with warnings.catch_warnings(record=True) as recorded:
            pickle.loads(pickle.dumps(p))
            msg = force_text(recorded.pop().message)
            self.assertEqual(msg,
                "Pickled model instance's Django version %s does not "
                "match the current version %s."
                % (str(float(get_major_version()) - 0.1), get_version()))
Example #23
0
    def add_arguments(self, parser):
        parser.add_argument('--worker-class', action='store', dest='worker_class',
                            default='rq.Worker', help='RQ Worker class to use')
        parser.add_argument('--pid', action='store', dest='pid',
                            default=None, help='PID file to write the worker`s pid into')
        parser.add_argument('--burst', action='store', dest='burst',
                            default=False, help='Run worker in burst mode')
        parser.add_argument('--name', action='store', dest='name',
                            default=None, help='Name of the worker')
        parser.add_argument('--queue-class', action='store', dest='queue_class',
                            default='django_rq.queues.DjangoRQ', help='Queues class to use')
        parser.add_argument('--worker-ttl', action='store', type=int,
                            dest='worker_ttl', default=420,
                            help='Default worker timeout to be used')
        parser.add_argument('--workers', '-w', action='store', type=int, dest='num_workers',
                            default=None, help='Number of workers to spawn, defaults to RQ_CONCURRENCY, or 1')
        parser.add_argument('--autoreload', action='store_true', dest='autoreload',
                            default=False, help='Enable autoreload of rqworkers for development')

        if LooseVersion(get_version()) >= LooseVersion('1.10'):
            parser.add_argument('args', nargs='*', type=str,
                                help='The queues to work on, separated by space')
Example #24
0
 def add_arguments(self, parser):
     parser.add_argument('queues',
                         nargs='*',
                         type=str,
                         help='The queues to work on, separated by space')
     parser.add_argument('--worker-class',
                         action='store',
                         dest='worker_class',
                         default='rq.Worker',
                         help='RQ Worker class to use')
     parser.add_argument('--pid',
                         action='store',
                         dest='pid',
                         default=None,
                         help='PID file to write the worker`s pid into')
     parser.add_argument('--burst',
                         action='store',
                         dest='burst',
                         default=False,
                         help='Run worker in burst mode')
     parser.add_argument('--name',
                         action='store',
                         dest='name',
                         default=None,
                         help='Name of the worker')
     parser.add_argument('--queue-class',
                         action='store',
                         dest='queue_class',
                         default='django_rq.queues.DjangoRQ',
                         help='Queues class to use')
     parser.add_argument('--worker-ttl',
                         action='store',
                         type=int,
                         dest='worker_ttl',
                         default=420,
                         help='Default worker timeout to be used')
     if LooseVersion(get_version()) >= LooseVersion('1.9'):
         parser.add_argument('args', nargs='*')
Example #25
0
# Use Django's template loader with Pystache's renderer
# NOTE: Support for multiple template engines was introduced in Django 1.8.
# This code includes hacks to support both 1.7 and 1.8.  When 1.9 comes out and
# we drop support for 1.7, we should be able to clean this up a bit.
from pystache.renderer import Renderer as PystacheRenderer
from django.template.loaders.filesystem import Loader as FileSystemLoader
from django.template.base import Template as DjangoTemplate
from django.utils.encoding import force_text
from django.utils.version import get_version

from django.utils.functional import empty
from django.utils.six import PY3
DJANGO18 = get_version() >= "1.8"


class Renderer(PystacheRenderer):
    def __init__(self, template, *args, **kwargs):
        self.template = template
        return super(Renderer, self).__init__(*args, **kwargs)

    def get_template_source(self, name):
        kwargs = {}
        if self.template.engine:
            kwargs['engine'] = self.template.engine
        template, origin = Loader(**kwargs).load_template(name)
        return template.source

    def _make_load_template(self):
        return self.get_template_source

    def _make_load_partial(self):
Example #26
0
from distutils.version import LooseVersion
from django import template
from django.utils.version import get_version

register = template.Library()

if LooseVersion(get_version()) >= LooseVersion('1.9'):
    JQUERY_PATH = 'admin/js/vendor/jquery/jquery.js'

    # `assignment_tag` is deprecated as of 1.9, `simple_tag` should be used
    tag_decorator = register.simple_tag
else:
    JQUERY_PATH = 'admin/js/jquery.js'
    tag_decorator = register.assignment_tag


@tag_decorator
def get_jquery_path():
    return JQUERY_PATH


@register.simple_tag
def get_jquery_path():
    return JQUERY_PATH
Example #27
0
def get_version(*args, **kwargs):
    # Don't litter django/__init__.py with all the get_version stuff.
    # Only import if it's actually called.
    from django.utils.version import get_version
    return get_version(*args, **kwargs)
Example #28
0
def get_version(*args, **kwargs):
    # Don't litter django/__init__.py with all the get_version stuff.
    # Only import if it's actually called.
    from django.utils.version import get_version
    return get_version(*args, **kwargs)
Example #29
0
 def __init__(self, *args, **kwargs):
     super(ReadOnlyAdminMixin, self).__init__(*args, **kwargs)
     if get_version() >= StrictVersion('1.9.0'):
         self.list_display_links = None
     else:
         self.list_display_links = (None, )
Example #30
0
 def test_unsupported_unpickle(self):
     """
     #21430 -- Verifies a warning is raised for querysets that are
     unpickled with a different Django version than the current
     """
     qs = Group.previous_django_version_objects.all()
     msg = "Pickled queryset instance's Django version 1.0 does not match the current version %s." % get_version()
     with self.assertRaisesMessage(RuntimeWarning, msg):
         pickle.loads(pickle.dumps(qs))
Example #31
0
def get_version(*args, **kwargs):
    from django.utils.version import get_version
    return get_version(*args, **kwargs)
Example #32
0
# encoding: utf-8

from django.utils.version import get_version


if get_version() < (1, 7, 0):
    from semantic_ui.patch import patch_all
    patch_all()
Example #33
0
__title__ = 'django-qartez'
__version__ = '0.7'
__build__ = 0x000007
__author__ = 'Artur Barseghyan <*****@*****.**>'

from django.utils import version

if version.get_version() < 1.9:
    from .sitemaps import *
Example #34
0
from distutils.version import LooseVersion
from django import template
from django.utils.version import get_version


register = template.Library()

if LooseVersion(get_version()) >= LooseVersion('1.9'):
    JQUERY_PATH = 'admin/js/vendor/jquery/jquery.js'

    # `assignment_tag` is deprecated as of 1.9, `simple_tag` should be used
    tag_decorator = register.simple_tag
else:
    JQUERY_PATH = 'admin/js/jquery.js'
    tag_decorator = register.assignment_tag


@register.assignment_tag
def get_jquery_path():
    return JQUERY_PATH
Example #35
0
def get_version():
    from django.utils.version import get_version
    return get_version(VERSION)
Example #36
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = '<a href="https://www.bounca.org">BounCA</a>'
copyright = '2016, Repleo, Amstelveen, Holland'
author = 'Jeroen Arnoldus'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = str(get_docs_version(VERSION))
# The full version, including alpha/beta/rc tags.
release = str(get_version(VERSION))

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
Example #37
0
from __future__ import unicode_literals

from django.utils.version import get_version

VERSION = (1, 10, 3, 'final', 0)

__version__ = get_version(VERSION)


def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.utils.encoding import force_text
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            '/' if settings.FORCE_SCRIPT_NAME is None else force_text(settings.FORCE_SCRIPT_NAME)
        )
    apps.populate(settings.INSTALLED_APPS)
 def __getstate__(self):
     '''pickle adapt, to prevent _fetch_all data'''
     obj_dict = self.__dict__.copy()
     obj_dict[DJANGO_VERSION_PICKLE_KEY] = get_version()
     return obj_dict
Example #39
0
 def __getitem__(self, item):
     if StrictVersion(version.get_version()) >= StrictVersion('1.9'):
         return None
     return 'notmigrations'
Example #40
0
from django import forms
from django.core.exceptions import ValidationError
from django.db import connections as pymongo_connections
from django.db import router, connections, transaction
from django.db.models import (Manager, Model, Field, AutoField, ForeignKey,
                              BigAutoField)
from django.utils import version
from django.db.models.fields.related import RelatedField
from django.forms import modelform_factory
from django.utils.functional import cached_property
from django.utils.html import format_html_join, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from djongo.exceptions import NotSupportedError, print_warn

django_major = int(version.get_version().split('.')[0])

if django_major >= 3:
    from django.db.models.fields import AutoFieldMixin, AutoFieldMeta


def make_mdl(model, model_dict):
    """
    Builds an instance of model from the model_dict.
    """
    for field_name in model_dict:
        field = model._meta.get_field(field_name)
        model_dict[field_name] = field.to_python(model_dict[field_name])

    return model(**model_dict)
Example #41
0
def get_version(*args, **kwargs):
    # Avoid circular import
    from django.utils.version import get_version
    return get_version(*args, **kwargs)
Example #42
0
    def test_unsupported_unpickle(self):
        """
        #21430 -- Verifies a warning is raised for models that are
        unpickled with a different Django version than the current
        """
        class DifferentDjangoVersion(models.Model):
            title = models.CharField(max_length=10)

            def __reduce__(self):
                reduce_list = super(DifferentDjangoVersion, self).__reduce__()
                data = reduce_list[-1]
                data[DJANGO_VERSION_PICKLE_KEY] = '1.0'
                return reduce_list

        p = DifferentDjangoVersion(title="FooBar")
        msg = "Pickled model instance's Django version 1.0 does not match the current version %s." % get_version()
        with self.assertRaisesMessage(RuntimeWarning, msg):
            pickle.loads(pickle.dumps(p))
Example #43
0
__title__ = 'django-qartez'
__version__ = '0.7.1'
__build__ = 0x000008
__author__ = 'Artur Barseghyan <*****@*****.**>'

from django.utils import version

if isinstance(version.get_version(), float) and version.get_version() < 1.9:
    from .sitemaps import *
Example #44
0
def get_version():
    from django.utils.version import get_version
    return get_version(VERSION)
Example #45
0
    def test_unsupported_unpickle(self):
        """
        #21430 -- Verifies a warning is raised for models that are
        unpickled with a different Django version than the current
        """
        class DifferentDjangoVersion(models.Model):
            title = models.CharField(max_length=10)

            def __reduce__(self):
                reduce_list = super(DifferentDjangoVersion, self).__reduce__()
                data = reduce_list[-1]
                data[DJANGO_VERSION_PICKLE_KEY] = '1.0'
                return reduce_list

        p = DifferentDjangoVersion(title="FooBar")
        msg = "Pickled model instance's Django version 1.0 does not match the current version %s." % get_version(
        )
        with self.assertRaisesMessage(RuntimeWarning, msg):
            pickle.loads(pickle.dumps(p))
Example #46
0
 def test_unsupported_unpickle(self):
     """
     #21430 -- Verifies a warning is raised for querysets that are
     unpickled with a different Django version than the current
     """
     qs = Group.previous_django_version_objects.all()
     msg = "Pickled queryset instance's Django version 1.0 does not match the current version %s." % get_version()
     with self.assertRaisesMessage(RuntimeWarning, msg):
         pickle.loads(pickle.dumps(qs))
Example #47
0
from __future__ import absolute_import

from django.utils import version
from django.db import IntegrityError
from django.contrib.gis.db.models import CharField
from django.core.exceptions import ValidationError
from django.test import TestCase
from tests import models
from etl_sync.generators import (
    get_unique_fields, get_unambiguous_fields, get_fields,
    BaseGenerator, InstanceGenerator, HashMixin)


VERSION = version.get_version()[2]


class TestUtils(TestCase):

    def test_get_unique_fields(self):
        self.assertEqual(
            get_unique_fields(models.Polish), ['record'])
        self.assertEqual(get_unique_fields(models.TwoUnique),
            ['record', 'anotherfield'])

    def test_get_unambigous_fields(self):
        results = [
            (models.TestModelWoFk, []),
            (models.Nombre, ['name']),
            (models.Polish, ['record']),
            (models.WellDefinedModel, ['something', 'somenumber'])
        ]
Example #48
0
# -*- coding: utf-8 -*-
import os

from django.utils.version import get_version

from setuptools import setup, find_packages

import log4django


setup(
    name='log4django',
    version=get_version(log4django.VERSION),
    description='log4django is full features logging platform for django applications.',
    long_description=open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
    author=u'Vladimír Gorej',
    author_email='*****@*****.**',
    url='http://www.codescale.net/en/community#log4django',
    download_url='http://github.com/CodeScaleInc/log4django/tarball/master',
    license='BSD',
    keywords='logging, django, log, logs',
    packages=find_packages('.'),
    install_requires = [
        'Django', 'django-model-utils', 'django-tastypie',
        'jsonpath', 'jsonpickle', 'mimeparse', 'python-dateutil'
    ],
    extras_require = {
        'gearman': ['gearman==dev', 'django-gearman-commands==dev'],
        'tests': ['mock']
    },
    platforms='any',
Example #49
0
# The master toctree document.
master_doc = 'index'

# General information about the project.
project = '<a href="https://www.bounca.org">BounCA</a>'
copyright = '2016, Repleo, Amstelveen, Holland'
author = 'Jeroen Arnoldus'

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = str(get_docs_version(VERSION))
# The full version, including alpha/beta/rc tags.
release = str(get_version(VERSION))

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'

# List of patterns, relative to source directory, that match files and
def get_cartoview_version(*args, **kwargs):  # carto compatible version
    # Don't litter django/__init__.py with all the get_version stuff.
    # Only import if it's actually called.
    from django.utils.version import get_version
    return get_version(version=CARTOVIEW_VERSION)
]


# Test/development settings.
DEBUG = True
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
    '--verbosity=2',
    '--no-path-adjustment',
    '--nocapture',
    '--all-modules',
    '--with-coverage',
    '--with-doctest',
]

if StrictVersion(get_version()) >= StrictVersion('1.8'):
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [
                os.path.join(os.path.dirname(__file__), "templates"),
            ],
            'OPTIONS': {
                'debug': DEBUG,
                'context_processors': [
                    # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                    # list if you haven't customized them:
                    'django.contrib.auth.context_processors.auth',
                    'django.template.context_processors.debug',
                    'django.template.context_processors.i18n',
                    'django.template.context_processors.media',
    "demoproject.nginx",  # Sample optimizations for Nginx X-Accel.
    "demoproject.apache",  # Sample optimizations for Apache X-Sendfile.
    "demoproject.lighttpd",  # Sample optimizations for Lighttpd X-Sendfile.
    # Standard Django applications.
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # Stuff that must be at the end.
    "django_nose",
)

# BEGIN middlewares
if StrictVersion(get_version()) >= StrictVersion("1.10"):
    MIDDLEWARE = [
        "django.middleware.common.CommonMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
        "django_downloadview.SmartDownloadMiddleware",
    ]
else:
    MIDDLEWARE_CLASSES = [
        "django.middleware.common.CommonMiddleware",
        "django.contrib.sessions.middleware.SessionMiddleware",
        "django.middleware.csrf.CsrfViewMiddleware",
        "django.contrib.auth.middleware.AuthenticationMiddleware",
        "django.contrib.messages.middleware.MessageMiddleware",
from django.utils.version import get_version

VERSION = (1, 8, 18, 'final', 0)

__version__ = get_version(VERSION)


def setup():
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    """
    from django.apps import apps
    from django.conf import settings
    from django.utils.log import configure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    apps.populate(settings.INSTALLED_APPS)
class RasterAggregatorTests(RasterTestCase):
    def test_layer_with_no_tiles(self):
        agg = Aggregator(layer_dict={
            'a': self.rasterlayer.id,
            'b': self.empty_rasterlayer.id
        },
                         formula='a*b')
        self.assertDictEqual(agg.value_count(), {})

    def test_layer_discrete_grouping(self):
        agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                         formula='a',
                         grouping='discrete')
        self.assertDictEqual(
            agg.value_count(),
            {str(k): v
             for k, v in self.expected_totals.items()})

    def test_layer_continuous_grouping(self):
        agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                         formula='a',
                         grouping='continuous')
        self.assertDictEqual(agg.value_count(),
                             self.continuous_expected_histogram)

    def test_layer_with_legend_grouping(self):
        # Use a legend with simple int expression
        agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                         formula='a',
                         grouping=self.legend.id)
        self.assertDictEqual(agg.value_count(), {'2': self.expected_totals[2]})
        # Use a legend with formula expression
        agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                         formula='a',
                         grouping=self.legend_with_expression.id)
        self.assertDictEqual(
            agg.value_count(), {
                '(x >= 2) & (x < 5)':
                self.expected_totals[2] + self.expected_totals[3] +
                self.expected_totals[4]
            })

    def test_layer_with_json_grouping(self):
        # Use a legend with simple int expression
        agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                         formula='a',
                         grouping=self.legend.json)
        self.assertDictEqual(agg.value_count(), {'2': self.expected_totals[2]})

    @skipIf(version.get_version() >= '1.9',
            'Fails on current release -- Refs #25734.')
    def test_layer_stats(self):
        # Use a legend with simple int expression
        agg = Aggregator(
            layer_dict={'a': self.rasterlayer.id},
            formula='a',
        )
        # Get original band metadata
        meta = self.rasterlayer.rasterlayerbandmetadata_set.first()
        # The comparison here is loose, as one is computed on tiles and the other
        # other value are the original band values. So there are differences from
        # rescaling.
        for dat in zip(agg.statistics(), meta.statistics()):
            self.assertAlmostEqual(dat[0], dat[1], 1)

    def test_valuecount_exception(self):
        # Invalid input type
        msg = 'Invalid grouping value found for valuecount.'
        with self.assertRaisesMessage(RasterAggregationException, msg):
            agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                             formula='a',
                             grouping='unknown')
            agg.value_count()

        # Invalid legend ID
        msg = 'Invalid legend ID found in grouping value for valuecount.'
        with self.assertRaisesMessage(RasterAggregationException, msg):
            agg = Aggregator(layer_dict={'a': self.rasterlayer.id},
                             formula='a',
                             grouping='99999')
Example #55
0
from distutils.version import StrictVersion

from django.utils.version import get_version

try:
    from django.conf.urls import patterns  # noqa
except ImportError:

    def patterns(prefix, *args):
        return list(args)


try:
    from django.urls import reverse  # noqa
except ImportError:
    from django.core.urlresolvers import reverse  # noqa

if StrictVersion(get_version()) >= StrictVersion("2.0"):
    from django.conf.urls import include as urlinclude  # noqa

    def include(arg, namespace=None, app_name=None):
        return urlinclude((arg, app_name), namespace=namespace)

else:
    from django.conf.urls import include  # noqa
Example #56
0
from . import views

# EAFP compliance with version 4.0
try:
    from django.conf.urls import url
except ImportError as e:
    from django.urls import re_path
    from django.utils import version

    # in case of any other error
    if int(version.get_version().split('.')[0]) >= 4:
        url = re_path
    else:
        raise ImportError(str(e))

urlpatterns = [
    url(r'^(?P<path_name>[\w_-]*)/(?P<format>[,\w-]+)/(?P<url>.*)/?$',
        views.resize,
        name="imagefit_resize"),
]