當前位置: 首頁>>代碼示例>>Python>>正文


Python six.memoryview方法代碼示例

本文整理匯總了Python中django.utils.six.memoryview方法的典型用法代碼示例。如果您正苦於以下問題:Python six.memoryview方法的具體用法?Python six.memoryview怎麽用?Python six.memoryview使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.six的用法示例。


在下文中一共展示了six.memoryview方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: fromfile

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def fromfile(file_h):
    """
    Given a string file name, returns a GEOSGeometry. The file may contain WKB,
    WKT, or HEX.
    """
    # If given a file name, get a real handle.
    if isinstance(file_h, six.string_types):
        with open(file_h, 'rb') as file_h:
            buf = file_h.read()
    else:
        buf = file_h.read()

    # If we get WKB need to wrap in memoryview(), so run through regexes.
    if isinstance(buf, bytes):
        try:
            decoded = buf.decode()
            if wkt_regex.match(decoded) or hex_regex.match(decoded):
                return GEOSGeometry(decoded)
        except UnicodeDecodeError:
            pass
    else:
        return GEOSGeometry(buf)

    return GEOSGeometry(six.memoryview(buf)) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:26,代碼來源:factory.py

示例2: __set__

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def __set__(self, obj, value):
        """
        This accessor sets the proxied geometry with the geometry class
        specified during initialization.  Values of None, HEXEWKB, or WKT may
        be used to set the geometry as well.
        """
        # The OGC Geometry type of the field.
        gtype = self._field.geom_type

        # The geometry type must match that of the field -- unless the
        # general GeometryField is used.
        if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'):
            # Assigning the SRID to the geometry.
            if value.srid is None:
                value.srid = self._field.srid
        elif value is None or isinstance(value, six.string_types + (six.memoryview,)):
            # Set with None, WKT, HEX, or WKB
            pass
        else:
            raise TypeError('Cannot set %s GeometryProxy (%s) with value of type: %s' % (
                obj.__class__.__name__, gtype, type(value)))

        # Setting the objects dictionary with the value, and returning.
        obj.__dict__[self._field.attname] = value
        return value 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:27,代碼來源:proxy.py

示例3: force_bytes

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    # Handle the common case first for performance reasons.
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if strings_only and is_protected_type(s):
        return s
    if isinstance(s, six.memoryview):
        return bytes(s)
    if isinstance(s, Promise):
        return six.text_type(s).encode(encoding, errors)
    if not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return b' '.join(force_bytes(arg, encoding, strings_only, errors)
                                 for arg in s)
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:37,代碼來源:encoding.py

示例4: quote_value

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def quote_value(self, value):
        # The backend "mostly works" without this function and there are use
        # cases for compiling Python without the sqlite3 libraries (e.g.
        # security hardening).
        import _sqlite3
        try:
            value = _sqlite3.adapt(value)
        except _sqlite3.ProgrammingError:
            pass
        # Manual emulation of SQLite parameter quoting
        if isinstance(value, type(True)):
            return str(int(value))
        elif isinstance(value, (Decimal, float)):
            return str(value)
        elif isinstance(value, six.integer_types):
            return str(value)
        elif isinstance(value, six.string_types):
            return "'%s'" % six.text_type(value).replace("\'", "\'\'")
        elif value is None:
            return "NULL"
        elif isinstance(value, (bytes, bytearray, six.memoryview)):
            # Bytes are only allowed for BLOB fields, encoded as string
            # literals containing hexadecimal data and preceded by a single "X"
            # character:
            # value = b'\x01\x02' => value_hex = b'0102' => return X'0102'
            value = bytes(value)
            hex_encoder = codecs.getencoder('hex_codec')
            value_hex, _length = hex_encoder(value)
            # Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
            return "X'%s'" % value_hex.decode('ascii')
        else:
            raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:34,代碼來源:schema.py

示例5: to_python

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def to_python(self, value):
        # If it's a string, it should be base64-encoded data
        if isinstance(value, six.text_type):
            return six.memoryview(b64decode(force_bytes(value)))
        return value 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:7,代碼來源:__init__.py

示例6: read

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def read(self, wkb):
        "Returns a _pointer_ to C GEOS Geometry object from the given WKB."
        if isinstance(wkb, six.memoryview):
            wkb_s = bytes(wkb)
            return wkb_reader_read(self.ptr, wkb_s, len(wkb_s))
        elif isinstance(wkb, (bytes, six.string_types)):
            return wkb_reader_read_hex(self.ptr, wkb, len(wkb))
        else:
            raise TypeError


# ### WKB/WKT Writer Classes ### 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:14,代碼來源:io.py

示例7: write

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def write(self, geom):
        "Returns the WKB representation of the given geometry."
        return six.memoryview(wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t()))) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:5,代碼來源:io.py

示例8: wkb

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def wkb(self):
        "Returns the WKB representation of the Geometry."
        if sys.byteorder == 'little':
            byteorder = 1  # wkbNDR (from ogr_core.h)
        else:
            byteorder = 0  # wkbXDR
        sz = self.wkb_size
        # Creating the unsigned character buffer, and passing it in by reference.
        buf = (c_ubyte * sz)()
        capi.to_wkb(self.ptr, byteorder, byref(buf))
        # Returning a buffer of the string at the pointer.
        return six.memoryview(string_at(buf, sz)) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:14,代碼來源:geometries.py

示例9: force_bytes

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if isinstance(s, six.memoryview):
        s = bytes(s)
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if strings_only and (s is None or isinstance(s, int)):
        return s
    if isinstance(s, Promise):
        return six.text_type(s).encode(encoding, errors)
    if not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return b' '.join([force_bytes(arg, encoding, strings_only,
                        errors) for arg in s])
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors) 
開發者ID:hughperkins,項目名稱:kgsgo-dataset-preprocessor,代碼行數:36,代碼來源:django_utils_encoding.py

示例10: quote_value

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def quote_value(self, value):
        # The backend "mostly works" without this function and there are use
        # cases for compiling Python without the sqlite3 libraries (e.g.
        # security hardening).
        try:
            import sqlite3
            value = sqlite3.adapt(value)
        except ImportError:
            pass
        except sqlite3.ProgrammingError:
            pass
        # Manual emulation of SQLite parameter quoting
        if isinstance(value, type(True)):
            return str(int(value))
        elif isinstance(value, (Decimal, float)):
            return str(value)
        elif isinstance(value, six.integer_types):
            return str(value)
        elif isinstance(value, six.string_types):
            return "'%s'" % six.text_type(value).replace("\'", "\'\'")
        elif value is None:
            return "NULL"
        elif isinstance(value, (bytes, bytearray, six.memoryview)):
            # Bytes are only allowed for BLOB fields, encoded as string
            # literals containing hexadecimal data and preceded by a single "X"
            # character:
            # value = b'\x01\x02' => value_hex = b'0102' => return X'0102'
            value = bytes(value)
            hex_encoder = codecs.getencoder('hex_codec')
            value_hex, _length = hex_encoder(value)
            # Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
            return "X'%s'" % value_hex.decode('ascii')
        else:
            raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) 
開發者ID:Yeah-Kun,項目名稱:python,代碼行數:36,代碼來源:schema.py

示例11: quote_value

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def quote_value(self, value):
        # The backend "mostly works" without this function and there are use
        # cases for compiling Python without the sqlite3 libraries (e.g.
        # security hardening).
        import sqlite3
        try:
            value = sqlite3.adapt(value)
        except sqlite3.ProgrammingError:
            pass
        # Manual emulation of SQLite parameter quoting
        if isinstance(value, type(True)):
            return str(int(value))
        elif isinstance(value, (Decimal, float)):
            return str(value)
        elif isinstance(value, six.integer_types):
            return str(value)
        elif isinstance(value, six.string_types):
            return "'%s'" % six.text_type(value).replace("\'", "\'\'")
        elif value is None:
            return "NULL"
        elif isinstance(value, (bytes, bytearray, six.memoryview)):
            # Bytes are only allowed for BLOB fields, encoded as string
            # literals containing hexadecimal data and preceded by a single "X"
            # character:
            # value = b'\x01\x02' => value_hex = b'0102' => return X'0102'
            value = bytes(value)
            hex_encoder = codecs.getencoder('hex_codec')
            value_hex, _length = hex_encoder(value)
            # Use 'ascii' encoding for b'01' => '01', no need to use force_text here.
            return "X'%s'" % value_hex.decode('ascii')
        else:
            raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) 
開發者ID:drexly,項目名稱:openhgsenti,代碼行數:34,代碼來源:schema.py

示例12: __init__

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def __init__(self, geo_input, srid=None):
        """
        The base constructor for GEOS geometry objects, and may take the
        following inputs:

         * strings:
            - WKT
            - HEXEWKB (a PostGIS-specific canonical form)
            - GeoJSON (requires GDAL)
         * buffer:
            - WKB

        The `srid` keyword is used to specify the Source Reference Identifier
        (SRID) number for this Geometry.  If not set, the SRID will be None.
        """
        if isinstance(geo_input, bytes):
            geo_input = force_text(geo_input)
        if isinstance(geo_input, six.string_types):
            wkt_m = wkt_regex.match(geo_input)
            if wkt_m:
                # Handling WKT input.
                if wkt_m.group('srid'):
                    srid = int(wkt_m.group('srid'))
                g = wkt_r().read(force_bytes(wkt_m.group('wkt')))
            elif hex_regex.match(geo_input):
                # Handling HEXEWKB input.
                g = wkb_r().read(force_bytes(geo_input))
            elif json_regex.match(geo_input):
                # Handling GeoJSON input.
                if not gdal.HAS_GDAL:
                    raise ValueError('Initializing geometry from JSON input requires GDAL.')
                g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb)
            else:
                raise ValueError('String or unicode input unrecognized as WKT EWKT, and HEXEWKB.')
        elif isinstance(geo_input, GEOM_PTR):
            # When the input is a pointer to a geometry (GEOM_PTR).
            g = geo_input
        elif isinstance(geo_input, six.memoryview):
            # When the input is a buffer (WKB).
            g = wkb_r().read(geo_input)
        elif isinstance(geo_input, GEOSGeometry):
            g = capi.geom_clone(geo_input.ptr)
        else:
            # Invalid geometry type.
            raise TypeError('Improper geometry input type: %s' % str(type(geo_input)))

        if g:
            # Setting the pointer object with a valid pointer.
            self.ptr = g
        else:
            raise GEOSException('Could not initialize GEOS Geometry with given input.')

        # Post-initialization setup.
        self._post_init(srid) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:56,代碼來源:geometry.py

示例13: __init__

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def __init__(self, geom_input, srs=None):
        "Initializes Geometry on either WKT or an OGR pointer as input."

        str_instance = isinstance(geom_input, six.string_types)

        # If HEX, unpack input to a binary buffer.
        if str_instance and hex_regex.match(geom_input):
            geom_input = six.memoryview(a2b_hex(geom_input.upper().encode()))
            str_instance = False

        # Constructing the geometry,
        if str_instance:
            wkt_m = wkt_regex.match(geom_input)
            json_m = json_regex.match(geom_input)
            if wkt_m:
                if wkt_m.group('srid'):
                    # If there's EWKT, set the SRS w/value of the SRID.
                    srs = int(wkt_m.group('srid'))
                if wkt_m.group('type').upper() == 'LINEARRING':
                    # OGR_G_CreateFromWkt doesn't work with LINEARRING WKT.
                    #  See http://trac.osgeo.org/gdal/ticket/1992.
                    g = capi.create_geom(OGRGeomType(wkt_m.group('type')).num)
                    capi.import_wkt(g, byref(c_char_p(wkt_m.group('wkt').encode())))
                else:
                    g = capi.from_wkt(byref(c_char_p(wkt_m.group('wkt').encode())), None, byref(c_void_p()))
            elif json_m:
                g = capi.from_json(geom_input.encode())
            else:
                # Seeing if the input is a valid short-hand string
                # (e.g., 'Point', 'POLYGON').
                OGRGeomType(geom_input)
                g = capi.create_geom(OGRGeomType(geom_input).num)
        elif isinstance(geom_input, six.memoryview):
            # WKB was passed in
            g = capi.from_wkb(bytes(geom_input), None, byref(c_void_p()), len(geom_input))
        elif isinstance(geom_input, OGRGeomType):
            # OGRGeomType was passed in, an empty geometry will be created.
            g = capi.create_geom(geom_input.num)
        elif isinstance(geom_input, self.ptr_type):
            # OGR pointer (c_void_p) was the input.
            g = geom_input
        else:
            raise GDALException('Invalid input type for OGR Geometry construction: %s' % type(geom_input))

        # Now checking the Geometry pointer before finishing initialization
        # by setting the pointer for the object.
        if not g:
            raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input))
        self.ptr = g

        # Assigning the SpatialReference object to the geometry, if valid.
        if srs:
            self.srs = srs

        # Setting the class depending upon the OGR Geometry Type
        self.__class__ = GEO_CLASSES[self.geom_type.num] 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:58,代碼來源:geometries.py

示例14: data

# 需要導入模塊: from django.utils import six [as 別名]
# 或者: from django.utils.six import memoryview [as 別名]
def data(self, data=None, offset=None, size=None, as_memoryview=False):
        """
        Reads or writes pixel values for this band. Blocks of data can
        be accessed by specifying the width, height and offset of the
        desired block. The same specification can be used to update
        parts of a raster by providing an array of values.

        Allowed input data types are bytes, memoryview, list, tuple, and array.
        """
        if not offset:
            offset = (0, 0)

        if not size:
            size = (self.width - offset[0], self.height - offset[1])

        if any(x <= 0 for x in size):
            raise ValueError('Offset too big for this raster.')

        if size[0] > self.width or size[1] > self.height:
            raise ValueError('Size is larger than raster.')

        # Create ctypes type array generator
        ctypes_array = GDAL_TO_CTYPES[self.datatype()] * (size[0] * size[1])

        if data is None:
            # Set read mode
            access_flag = 0
            # Prepare empty ctypes array
            data_array = ctypes_array()
        else:
            # Set write mode
            access_flag = 1

            # Instantiate ctypes array holding the input data
            if isinstance(data, (bytes, six.memoryview)) or (numpy and isinstance(data, numpy.ndarray)):
                data_array = ctypes_array.from_buffer_copy(data)
            else:
                data_array = ctypes_array(*data)

        # Access band
        capi.band_io(self._ptr, access_flag, offset[0], offset[1],
                     size[0], size[1], byref(data_array), size[0],
                     size[1], self.datatype(), 0, 0)

        # Return data as numpy array if possible, otherwise as list
        if data is None:
            if as_memoryview:
                return memoryview(data_array)
            elif numpy:
                return numpy.frombuffer(
                    data_array, dtype=numpy.dtype(data_array)).reshape(size)
            else:
                return list(data_array)
        else:
            self.source._flush() 
開發者ID:drexly,項目名稱:openhgsenti,代碼行數:57,代碼來源:band.py


注:本文中的django.utils.six.memoryview方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。