Python django.utils.six.PY3 Examples

The following are 30 code examples of django.utils.six.PY3(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.six , or try the search function .
Example #1
Source File: xadmin_tags.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
def view_block(context, block_name, *args, **kwargs):
    if 'admin_view' not in context:
        return ""

    admin_view = context['admin_view']
    nodes = []
    method_name = 'block_%s' % block_name

    cls_str = str if six.PY3 else basestring
    for view in [admin_view] + admin_view.plugins:
        if hasattr(view, method_name) and callable(getattr(view, method_name)):
            block_func = getattr(view, method_name)
            result = block_func(context, nodes, *args, **kwargs)
            if result and isinstance(result, cls_str):
                nodes.append(result)
    if nodes:
        return mark_safe(''.join(nodes))
    else:
        return "" 
Example #2
Source File: actions.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def get_actions(self):
        if self.actions is None:
            return OrderedDict()

        actions = [self.get_action(action) for action in self.global_actions]

        for klass in self.admin_view.__class__.mro()[::-1]:
            class_actions = getattr(klass, 'actions', [])
            if not class_actions:
                continue
            actions.extend(
                [self.get_action(action) for action in class_actions])

        # get_action might have returned None, so filter any of those out.
        actions = filter(None, actions)
        if six.PY3:
            actions = list(actions)

        # Convert the actions into a OrderedDict keyed by name.
        actions = OrderedDict([
            (name, (ac, name, desc, icon))
            for ac, name, desc, icon in actions
        ])

        return actions 
Example #3
Source File: xadmin_tags.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def view_block(context, block_name, *args, **kwargs):
    if 'admin_view' not in context:
        return ""

    admin_view = context['admin_view']
    nodes = []
    method_name = 'block_%s' % block_name

    cls_str = str if six.PY3 else basestring
    for view in [admin_view] + admin_view.plugins:
        if hasattr(view, method_name) and callable(getattr(view, method_name)):
            block_func = getattr(view, method_name)
            result = block_func(context, nodes, *args, **kwargs)
            if result and isinstance(result, cls_str):
                nodes.append(result)
    if nodes:
        return mark_safe(''.join(nodes))
    else:
        return "" 
Example #4
Source File: util.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def unquote(s):
    """
    Undo the effects of quote(). Based heavily on urllib.unquote().
    """
    cls_str = str if six.PY3 else basestring
    if not isinstance(s, cls_str):
        return s
    mychr = chr
    myatoi = int
    list = s.split('_')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16)) + item[2:])
            except ValueError:
                myappend('_' + item)
        else:
            myappend('_' + item)
    return "".join(res) 
Example #5
Source File: edit.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        self.instance_forms()
        self.setup_forms()

        if self.valid_forms():
            self.save_forms()
            self.save_models()
            self.save_related()
            response = self.post_response()
            cls_str = str if six.PY3 else basestring
            if isinstance(response, cls_str):
                return HttpResponseRedirect(response)
            else:
                return response

        return self.get_response() 
Example #6
Source File: filters.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def __init__(self, field, request, params, model, admin_view, field_path):
        self.field = field
        self.field_path = field_path
        self.title = getattr(field, 'verbose_name', field_path)
        self.context_params = {}

        super(FieldFilter, self).__init__(request, params, model, admin_view)

        for name, format in self.lookup_formats.items():
            p = format % field_path
            self.context_params["%s_name" % name] = FILTER_PREFIX + p
            if p in params:
                value = prepare_lookup_value(p, params.pop(p))
                self.used_params[p] = value
                self.context_params["%s_val" % name] = value
            else:
                self.context_params["%s_val" % name] = ''

        arr = map(
                lambda kv: setattr(self, 'lookup_' + kv[0], kv[1]),
                self.context_params.items()
                )
        if six.PY3:
            list(arr) 
Example #7
Source File: crypto.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def constant_time_compare(val1, val2):
        """
        Returns True if the two strings are equal, False otherwise.

        The time taken is independent of the number of characters that match.

        For the sake of simplicity, this function executes in constant time only
        when the two strings have the same length. It short-circuits when they
        have different lengths. Since Django only uses it to compare hashes of
        known expected length, this is acceptable.
        """
        if len(val1) != len(val2):
            return False
        result = 0
        if six.PY3 and isinstance(val1, bytes) and isinstance(val2, bytes):
            for x, y in zip(val1, val2):
                result |= x ^ y
        else:
            for x, y in zip(val1, val2):
                result |= ord(x) ^ ord(y)
        return result == 0 
Example #8
Source File: questioner.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _ask_default(self):
        print("Please enter the default value now, as valid Python")
        print("The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()")
        while True:
            if six.PY3:
                # Six does not correctly abstract over the fact that
                # py3 input returns a unicode string, while py2 raw_input
                # returns a bytestring.
                code = input(">>> ")
            else:
                code = input(">>> ").decode(sys.stdin.encoding)
            if not code:
                print("Please enter some code, or 'exit' (with no quotes) to exit.")
            elif code == "exit":
                sys.exit(1)
            else:
                try:
                    return eval(code, {}, {"datetime": datetime_safe, "timezone": timezone})
                except (SyntaxError, NameError) as e:
                    print("Invalid input: %s" % e) 
Example #9
Source File: manager.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _get_queryset_methods(cls, queryset_class):
        def create_method(name, method):
            def manager_method(self, *args, **kwargs):
                return getattr(self.get_queryset(), name)(*args, **kwargs)
            manager_method.__name__ = method.__name__
            manager_method.__doc__ = method.__doc__
            return manager_method

        new_methods = {}
        # Refs http://bugs.python.org/issue1785.
        predicate = inspect.isfunction if six.PY3 else inspect.ismethod
        for name, method in inspect.getmembers(queryset_class, predicate=predicate):
            # Only copy missing methods.
            if hasattr(cls, name):
                continue
            # Only copy public methods or methods with the attribute `queryset_only=False`.
            queryset_only = getattr(method, 'queryset_only', None)
            if queryset_only or (queryset_only is None and name.startswith('_')):
                continue
            # Copy the method onto the manager.
            new_methods[name] = create_method(name, method)
        return new_methods 
Example #10
Source File: makemessages.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def gettext_popen_wrapper(args, os_err_exc_type=CommandError, stdout_encoding="utf-8"):
    """
    Makes sure text obtained from stdout of gettext utilities is Unicode.
    """
    # This both decodes utf-8 and cleans line endings. Simply using
    # popen_wrapper(universal_newlines=True) doesn't properly handle the
    # encoding. This goes back to popen's flaky support for encoding:
    # https://bugs.python.org/issue6135. This is a solution for #23271, #21928.
    # No need to do anything on Python 2 because it's already a byte-string there.
    manual_io_wrapper = six.PY3 and stdout_encoding != DEFAULT_LOCALE_ENCODING

    stdout, stderr, status_code = popen_wrapper(args, os_err_exc_type=os_err_exc_type,
                                                universal_newlines=not manual_io_wrapper)
    if manual_io_wrapper:
        stdout = io.TextIOWrapper(io.BytesIO(stdout), encoding=stdout_encoding).read()
    if six.PY2:
        stdout = stdout.decode(stdout_encoding)
    return stdout, stderr, status_code 
Example #11
Source File: edit.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        self.instance_forms()
        self.setup_forms()

        if self.valid_forms():
            self.save_forms()
            self.save_models()
            self.save_related()
            response = self.post_response()
            cls_str = str if six.PY3 else basestring
            if isinstance(response, cls_str):
                return HttpResponseRedirect(response)
            else:
                return response

        return self.get_response() 
Example #12
Source File: util.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def unquote(s):
    """
    Undo the effects of quote(). Based heavily on urllib.unquote().
    """
    cls_str = str if six.PY3 else basestring
    if not isinstance(s, cls_str):
        return s
    mychr = chr
    myatoi = int
    list = s.split('_')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16)) + item[2:])
            except ValueError:
                myappend('_' + item)
        else:
            myappend('_' + item)
    return "".join(res) 
Example #13
Source File: xadmin_tags.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def view_block(context, block_name, *args, **kwargs):
    if 'admin_view' not in context:
        return ""

    admin_view = context['admin_view']
    nodes = []
    method_name = 'block_%s' % block_name

    cls_str = str if six.PY3 else basestring
    for view in [admin_view] + admin_view.plugins:
        if hasattr(view, method_name) and callable(getattr(view, method_name)):
            block_func = getattr(view, method_name)
            result = block_func(context, nodes, *args, **kwargs)
            if result and isinstance(result, cls_str):
                nodes.append(result)
    if nodes:
        return mark_safe(''.join(nodes))
    else:
        return "" 
Example #14
Source File: actions.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def get_actions(self):
        if self.actions is None:
            return OrderedDict()

        actions = [self.get_action(action) for action in self.global_actions]

        for klass in self.admin_view.__class__.mro()[::-1]:
            class_actions = getattr(klass, 'actions', [])
            if not class_actions:
                continue
            actions.extend(
                [self.get_action(action) for action in class_actions])

        # get_action might have returned None, so filter any of those out.
        actions = filter(None, actions)
        if six.PY3:
            actions = list(actions)

        # Convert the actions into a OrderedDict keyed by name.
        actions = OrderedDict([
            (name, (ac, name, desc, icon))
            for ac, name, desc, icon in actions
        ])

        return actions 
Example #15
Source File: filters.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, field, request, params, model, admin_view, field_path):
        self.field = field
        self.field_path = field_path
        self.title = getattr(field, 'verbose_name', field_path)
        self.context_params = {}

        super(FieldFilter, self).__init__(request, params, model, admin_view)

        for name, format in self.lookup_formats.items():
            p = format % field_path
            self.context_params["%s_name" % name] = FILTER_PREFIX + p
            if p in params:
                value = prepare_lookup_value(p, params.pop(p))
                self.used_params[p] = value
                self.context_params["%s_val" % name] = value
            else:
                self.context_params["%s_val" % name] = ''

        arr = map(
            lambda kv: setattr(self, 'lookup_' + kv[0], kv[1]),
            self.context_params.items()
        )
        if six.PY3:
            list(arr) 
Example #16
Source File: edit.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request, *args, **kwargs):
        self.instance_forms()
        self.setup_forms()

        if self.valid_forms():
            self.save_forms()
            self.save_models()
            self.save_related()
            response = self.post_response()
            cls_str = str if six.PY3 else basestring
            if isinstance(response, cls_str):
                return HttpResponseRedirect(response)
            else:
                return response

        return self.get_response() 
Example #17
Source File: util.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
def unquote(s):
    """
    Undo the effects of quote(). Based heavily on urllib.unquote().
    """
    cls_str = str if six.PY3 else basestring
    if not isinstance(s, cls_str):
        return s
    mychr = chr
    myatoi = int
    list = s.split('_')
    res = [list[0]]
    myappend = res.append
    del list[0]
    for item in list:
        if item[1:2]:
            try:
                myappend(mychr(myatoi(item[:2], 16)) + item[2:])
            except ValueError:
                myappend('_' + item)
        else:
            myappend('_' + item)
    return "".join(res) 
Example #18
Source File: basehttp.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_environ(self):
        # Strip all headers with underscores in the name before constructing
        # the WSGI environ. This prevents header-spoofing based on ambiguity
        # between underscores and dashes both normalized to underscores in WSGI
        # env vars. Nginx and Apache 2.4+ both do this as well.
        for k, v in self.headers.items():
            if '_' in k:
                del self.headers[k]

        env = super(WSGIRequestHandler, self).get_environ()

        path = self.path
        if '?' in path:
            path = path.partition('?')[0]

        path = uri_to_iri(path).encode(UTF_8)
        # Under Python 3, non-ASCII values in the WSGI environ are arbitrarily
        # decoded with ISO-8859-1. We replicate this behavior here.
        # Refs comment in `get_bytes_from_wsgi()`.
        env['PATH_INFO'] = path.decode(ISO_8859_1) if six.PY3 else path

        return env 
Example #19
Source File: filters.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def __init__(self, field, request, params, model, admin_view, field_path):
        self.field = field
        self.field_path = field_path
        self.title = getattr(field, 'verbose_name', field_path)
        self.context_params = {}

        super(FieldFilter, self).__init__(request, params, model, admin_view)

        for name, format in self.lookup_formats.items():
            p = format % field_path
            self.context_params["%s_name" % name] = FILTER_PREFIX + p
            if p in params:
                value = prepare_lookup_value(p, params.pop(p))
                self.used_params[p] = value
                self.context_params["%s_val" % name] = value
            else:
                self.context_params["%s_val" % name] = ''

        arr = map(
            lambda kv: setattr(self, 'lookup_' + kv[0], kv[1]),
            self.context_params.items()
        )
        if six.PY3:
            list(arr) 
Example #20
Source File: detail.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def get_form_helper(self):
        helper = FormHelper()
        helper.form_tag = False
        helper.include_media = False
        layout = self.get_form_layout()
        replace_field_to_value(layout, self.get_field_result)
        helper.add_layout(layout)
        cls_str = str if six.PY3 else basestring
        helper.filter(cls_str, max_level=20).wrap(ShowField, admin_view=self)
        return helper 
Example #21
Source File: util.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def xstatic(*tags):
    from .vendors import vendors
    node = vendors

    fs = []
    lang = get_language()

    cls_str = str if six.PY3 else basestring
    for tag in tags:
        try:
            for p in tag.split('.'):
                node = node[p]
        except Exception as e:
            if tag.startswith('xadmin'):
                file_type = tag.split('.')[-1]
                if file_type in ('css', 'js'):
                    node = "xadmin/%s/%s" % (file_type, tag)
                else:
                    raise e
            else:
                raise e

        if isinstance(node, cls_str):
            files = node
        else:
            mode = 'dev'
            if not settings.DEBUG:
                mode = getattr(settings, 'STATIC_USE_CDN',
                               False) and 'cdn' or 'production'

            if mode == 'cdn' and mode not in node:
                mode = 'production'
            if mode == 'production' and mode not in node:
                mode = 'dev'
            files = node[mode]

        files = type(files) in (list, tuple) and files or [files, ]
        fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])

    return [f.startswith('http://') and f or static(f) for f in fs] 
Example #22
Source File: detail.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def replace_field_to_value(layout, cb):
    cls_str = str if six.PY3 else basestring
    for i, lo in enumerate(layout.fields):
        if isinstance(lo, Field) or issubclass(lo.__class__, Field):
            layout.fields[i] = ShowField(
                cb, *lo.fields, attrs=lo.attrs, wrapper_class=lo.wrapper_class)
        elif isinstance(lo, cls_str):
            layout.fields[i] = ShowField(cb, lo)
        elif hasattr(lo, 'get_field_names'):
            replace_field_to_value(lo, cb) 
Example #23
Source File: edit.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def get_form_layout(self):
        layout = copy.deepcopy(self.form_layout)
        arr = self.form_obj.fields.keys()
        if six.PY3:
            arr = [k for k in arr]
        fields = arr + list(self.get_readonly_fields())

        if layout is None:
            layout = Layout(Container(Col('full',
                                          Fieldset("", *fields, css_class="unsort no_title"), horizontal=True, span=12)
                                      ))
        elif type(layout) in (list, tuple) and len(layout) > 0:
            if isinstance(layout[0], Column):
                fs = layout
            elif isinstance(layout[0], (Fieldset, TabHolder)):
                fs = (Col('full', *layout, horizontal=True, span=12),)
            else:
                fs = (Col('full', Fieldset("", *layout, css_class="unsort no_title"), horizontal=True, span=12),)

            layout = Layout(Container(*fs))

            rendered_fields = [i[1] for i in layout.get_field_names()]
            container = layout[0].fields
            other_fieldset = Fieldset(_(u'Other Fields'), *[f for f in fields if f not in rendered_fields])

            if len(other_fieldset.fields):
                if len(container) and isinstance(container[0], Column):
                    container[0].fields.append(other_fieldset)
                else:
                    container.append(other_fieldset)

        return layout 
Example #24
Source File: inline.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def replace_field_to_value(layout, av):
    if layout:
        cls_str = str if six.PY3 else basestring
        for i, lo in enumerate(layout.fields):
            if isinstance(lo, Field) or issubclass(lo.__class__, Field):
                layout.fields[i] = ShowField(av, *lo.fields, **lo.attrs)
            elif isinstance(lo, cls_str):
                layout.fields[i] = ShowField(av, lo)
            elif hasattr(lo, 'get_field_names'):
                replace_field_to_value(lo, av) 
Example #25
Source File: relate.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def post_response(self, response):
        cls_str = str if six.PY3 else basestring
        if isinstance(response, cls_str) and response != self.get_admin_url('index'):
            return self._get_url(response)
        return response 
Example #26
Source File: filters.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def get_context(self):
        context = super(FieldFilter, self).get_context()
        context.update(self.context_params)
        obj = map(lambda k: FILTER_PREFIX + k, self.used_params.keys())
        if six.PY3:
            obj = list(obj)
        context['remove_url'] = self.query_string({}, obj)
        return context 
Example #27
Source File: relate.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def post_response(self, response):
        cls_str = str if six.PY3 else basestring
        if isinstance(response, cls_str) and response != self.get_admin_url('index'):
            return self._get_url(response)
        return response 
Example #28
Source File: wizard.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def _get_form_prefix(self, step=None):
        if step is None:
            step = self.steps.current
        obj = self.get_form_list().keys()
        if six.PY3:
            obj = [s for s in obj]
        return 'step_%d' % obj.index(step) 
Example #29
Source File: wizard.py    From weibo-analysis-system with MIT License 5 votes vote down vote up
def get_next_step(self, step=None):
        """
        Returns the next step after the given `step`. If no more steps are
        available, None will be returned. If the `step` argument is None, the
        current step will be determined automatically.
        """
        if step is None:
            step = self.steps.current
        obj = self.get_form_list().keys()
        if six.PY3:
            obj = [s for s in obj]
        key = obj.index(step) + 1
        if len(obj) > key:
            return obj[key]
        return None 
Example #30
Source File: detail.py    From StormOnline with Apache License 2.0 5 votes vote down vote up
def replace_field_to_value(layout, cb):
    cls_str = str if six.PY3 else basestring
    for i, lo in enumerate(layout.fields):
        if isinstance(lo, Field) or issubclass(lo.__class__, Field):
            layout.fields[i] = ShowField(
                cb, *lo.fields, attrs=lo.attrs, wrapper_class=lo.wrapper_class)
        elif isinstance(lo, cls_str):
            layout.fields[i] = ShowField(cb, lo)
        elif hasattr(lo, 'get_field_names'):
            replace_field_to_value(lo, cb)