How to use the spyne.util.six function in spyne

To help you get started, we’ve selected a few spyne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github arskom / spyne / spyne / util / _base.py View on Github external
@memoize
def get_version(package):
    if isinstance(package, (six.text_type, six.binary_type)):
        package = __import__(package)

    verstr = getattr(package, '__version__')
    retval = []

    for f in verstr.split("."):
        try:
            retval.append(int(f))
        except ValueError:
            retval.append(f)

    return tuple(retval)
github arskom / spyne / spyne / descriptor.py View on Github external
if pc is not None:
            mn = pc.__module__
            on = pc.__name__

            dn = self.name
            # prevent duplicate class name. this happens when the class is a
            # direct subclass of ComplexModel
            if dn.split('.', 1)[0] != on:
                return "{%s}%s.%s" % (mn, on, dn)

            return "{%s}%s" % (mn, dn)

        sc = self.service_class
        if sc is not None:
            return '{%s}%s%s' % (sc.get_internal_key(),
                                    six.get_function_name(self.function),
                                                       self.internal_key_suffix)
github arskom / spyne / spyne / store / relational / document.py View on Github external
def process(value):
            if isinstance(value, (text_type, binary_type)) or value is None:
                return value
            else:
                if six.PY2:
                    return json.dumps(value, encoding=self.encoding)
                else:
                    return json.dumps(value)
        return process
github arskom / spyne / spyne / protocol / http.py View on Github external
import logging
logger = logging.getLogger(__name__)

import re
import pytz
import tempfile

from spyne import BODY_STYLE_WRAPPED, MethodDescriptor, PushBase
from spyne.util import six, coroutine, Break
from spyne.util.six import string_types, BytesIO
from spyne.error import ResourceNotFoundError
from spyne.model.binary import BINARY_ENCODING_URLSAFE_BASE64, File
from spyne.model.primitive import DateTime
from spyne.protocol.dictdoc import SimpleDictDocument

if six.PY2:
    from Cookie import SimpleCookie
else:
    from http.cookies import SimpleCookie


TEMPORARY_DIR = None
STREAM_READ_BLOCK_SIZE = 0x4000
SWAP_DATA_TO_FILE_THRESHOLD = 512 * 1024


def get_stream_factory(dir=None, delete=True):
    def stream_factory(total_content_length, filename, content_type,
                                                           content_length=None):
        if total_content_length >= SWAP_DATA_TO_FILE_THRESHOLD or \
                                                                delete == False:
            if delete == False:
github arskom / spyne / spyne / protocol / dictdoc.py View on Github external
member = simple_type_info.get(k, None)
            if member is None:
                logger.debug("\tdiscarding field %r" % k)
                continue

            # extract native values from the list of strings in the flat dict
            # entries.
            value = []
            for v2 in v:
                # some wsgi implementations pass unicode strings, some pass str
                # strings. we get unicode here when we can and should.
                if v2 is not None and req_enc is not None \
                                        and not issubclass(member.type, String) \
                                        and issubclass(member.type, Unicode) \
                                        and not isinstance(v2, six.text_type):
                    try:
                        v2 = v2.decode(req_enc)
                    except UnicodeDecodeError as e:
                        raise ValidationError(v2, "%r while decoding %%r" % e)

                try:
                    if (validator is self.SOFT_VALIDATION and not
                                  member.type.validate_string(member.type, v2)):
                        raise ValidationError((orig_k, v2))

                except TypeError:
                    raise ValidationError((orig_k, v2))

                if issubclass(member.type, File):
                    if isinstance(v2, File.Value):
                        native_v2 = v2
github arskom / spyne / spyne / model / primitive / number.py View on Github external
UnsignedInteger8 = TBoundedUnsignedInteger(8, 'unsignedByte')
"""The 8-bit unsigned integer, also known as ``unsignedByte``."""

UnsignedByte = UnsignedInteger8
"""The 8-bit unsigned integer, alias for :class:`UnsignedInteger8`."""


NATIVE_MAP.update({
    float: Double,
    decimal.Decimal: Decimal,
})


if not six.PY2:
    NATIVE_MAP.update({
        int: Integer,
    })

else:
    NATIVE_MAP.update({
        long: Integer,
    })

    if isinstance(0x80000000, long):  # 32-bit architecture
        NATIVE_MAP[int] = Integer32
    else:  # not 32-bit (so most probably 64-bit) architecture
        NATIVE_MAP[int] = Integer64
github arskom / spyne / spyne / protocol / dictdoc / hier.py View on Github external
def validate(self, key, cls, inst):
        if inst is None and self.get_cls_attrs(cls).nullable:
            pass

        elif issubclass(cls, Unicode) and not isinstance(inst,(six.text_type,
                                                               six.binary_type)):
            raise ValidationError([key, inst])
github arskom / spyne / spyne / protocol / _base.py View on Github external
def unicode_to_string(self, cls, value):
        retval = value
        if cls.Attributes.encoding is not None and \
                                               isinstance(value, six.text_type):
            retval = value.encode(cls.Attributes.encoding)
        if cls.Attributes.format is None:
            return retval
        else:
            return cls.Attributes.format % retval
github arskom / spyne / spyne / model / primitive.py View on Github external
store_as = apply_pssm(kwargs.get('store_as', None),
                                {'json': json, 'xml': xml, 'msgpack': msgpack})
        if store_as is not None:
            kwargs['store_as'] = store_as

        return super(AnyDict, cls).customize(**kwargs)


class Unicode(SimpleModel):
    """The type to represent human-readable data. Its native format is `unicode`
    or `str` with given encoding.
    """

    __type_name__ = 'string'
    Value = six.text_type

    class Attributes(SimpleModel.Attributes):
        """Customizable attributes of the :class:`spyne.model.primitive.Unicode`
        type."""

        min_len = 0
        """Minimum length of string. Can be set to any positive integer"""

        max_len = decimal.Decimal('inf')
        """Maximum length of string. Can be set to ``decimal.Decimal('inf')`` to
        accept strings of arbitrary length. You may also need to adjust
        :const:`spyne.server.wsgi.MAX_CONTENT_LENGTH`."""

        pattern = None
        """A regular expression that matches the whole string. See here for more
        info: http://www.regular-expressions.info/xml.html"""
github arskom / spyne / spyne / protocol / _outbase.py View on Github external
def unicode_to_unicode(self, cls, value, **_):  # :)))
        cls_attrs = self.get_cls_attrs(cls)

        retval = value

        if isinstance(value, six.binary_type):
            if cls_attrs.encoding is not None:
                retval = value.decode(cls_attrs.encoding)

            if self.default_string_encoding is not None:
                retval = value.decode(self.default_string_encoding)

            elif not six.PY2:
                logger.warning("You need to set either an encoding for %r "
                               "or a default_string_encoding for %r", cls, self)

        if cls_attrs.str_format is not None:
            return cls_attrs.str_format.format(value)
        elif cls_attrs.format is not None:
            return cls_attrs.format % retval

        return retval