desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Writes a C{tuple}, C{set} or C{list} to the stream. @type n: One of C{__builtin__.tuple}, C{__builtin__.set} or C{__builtin__.list} @param n: The C{list} data to be encoded to the AMF3 data stream.'
def writeList(self, n, is_proxy=False):
if (self.use_proxies and (not is_proxy)): self.writeProxy(n) return self.stream.write(TYPE_ARRAY) ref = self.context.getObjectReference(n) if (ref != (-1)): self._writeInteger((ref << 1)) return self.context.addObject(n) self._writeInteger(((len(n) << 1) | REFEREN...
'Writes a C{dict} to the stream. @type n: C{__builtin__.dict} @param n: The C{dict} data to be encoded to the AMF3 data stream. @raise ValueError: Non C{int}/C{str} key value found in the C{dict} @raise EncodeError: C{dict} contains empty string keys.'
def writeDict(self, n):
if ('' in n): raise pyamf.EncodeError('dicts cannot contain empty string keys') if self.use_proxies: self.writeProxy(n) return self.stream.write(TYPE_ARRAY) ref = self.context.getObjectReference(n) if (ref != (-1)): self._writeInteger((ref << 1)) ...
'Encodes a proxied object to the stream. @since: 0.6'
def writeProxy(self, obj):
proxy = self.context.getProxyForObject(obj) self.writeObject(proxy, is_proxy=True)
'Writes an object to the stream.'
def writeObject(self, obj, is_proxy=False):
if (self.use_proxies and (not is_proxy)): self.writeProxy(obj) return self.stream.write(TYPE_OBJECT) ref = self.context.getObjectReference(obj) if (ref != (-1)): self._writeInteger((ref << 1)) return self.context.addObject(obj) kls = obj.__class__ definition =...
'Writes a L{ByteArray} to the data stream. @param n: The L{ByteArray} data to be encoded to the AMF3 data stream. @type n: L{ByteArray}'
def writeByteArray(self, n):
self.stream.write(TYPE_BYTEARRAY) ref = self.context.getObjectReference(n) if (ref != (-1)): self._writeInteger((ref << 1)) return self.context.addObject(n) buf = str(n) l = len(buf) self._writeInteger(((l << 1) | REFERENCE_BIT)) self.stream.write(buf)
'Writes a XML string to the data stream. @type n: L{ET<xml.ET>} @param n: The XML Document to be encoded to the AMF3 data stream.'
def writeXML(self, n):
self.stream.write(TYPE_XMLSTRING) ref = self.context.getObjectReference(n) if (ref != (-1)): self._writeInteger((ref << 1)) return self.context.addObject(n) self.serialiseString(xml.tostring(n).encode('utf-8'))
'Return an instance based on klass/key. If an instance cannot be found then C{KeyError} is raised. @param klass: The class of the instance. @param key: The primary_key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of C{klass}.'
def getClassKey(self, klass, key):
d = self._getClass(klass) return d[key]
'Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore.'
def addClassKey(self, klass, key, obj):
d = self._getClass(klass) d[key] = obj
'Returns a C{tuple} containing a dict of static and dynamic attributes for C{obj}.'
def getEncodableAttributes(self, obj, **kwargs):
attrs = pyamf.ClassAlias.getEncodableAttributes(self, obj, **kwargs) if (not self.exclude_sa_key): attrs[self.KEY_ATTR] = self.mapper.primary_key_from_instance(obj) if (not self.exclude_sa_lazy): lazy_attrs = [] for attr in self.properties: if (attr not in obj.__dict__): ...
''
def getDecodableAttributes(self, obj, attrs, **kwargs):
attrs = pyamf.ClassAlias.getDecodableAttributes(self, obj, attrs, **kwargs) if (self.LAZY_ATTR in attrs): obj_state = None if hasattr(orm.attributes, 'instance_state'): obj_state = orm.attributes.instance_state(obj) for lazy_attr in attrs[self.LAZY_ATTR]: if (lazy...
'Return an instance based on klass/key. If an instance cannot be found then C{KeyError} is raised. @param klass: The class of the instance. @param key: The key of the instance. @return: The instance linked to the C{klass}/C{key}. @rtype: Instance of L{klass}.'
def getClassKey(self, klass, key):
d = self._getClass(klass) return d[key]
'Adds an object to the collection, based on klass and key. @param klass: The class of the object. @param key: The datastore key of the object. @param obj: The loaded instance from the datastore.'
def addClassKey(self, klass, key, obj):
d = self._getClass(klass) d[key] = obj
'Returns a dict of kay/value pairs for PyAMF to encode.'
def getEncodableAttributes(self, obj, codec=None):
attrs = {'content_type': obj.content_type, 'filename': obj.filename, 'size': obj.size, 'creation': obj.creation, 'key': str(obj.key())} return attrs
'Applies C{attrs} to C{obj}. Since C{blobstore.BlobInfo} objects are read-only entities, we only care about the C{key} attribute.'
def applyAttributes(self, obj, attrs, **kwargs):
assert (type(obj) is BlobInfoStub) key = attrs.pop('key', None) if (not key): raise pyamf.DecodeError("Unable to build blobstore.BlobInfo instance. Missing 'key' attribute.") try: key = blobstore.BlobKey(key) except: raise pyamf.DecodeError(('Unable to...
'Called when an import is made. If there are hooks waiting for this module to be imported then we stop the normal import process and manually load the module. @param name: The name of the module being imported. @param path The root path of the module (if a package). We ignore this. @return: If we want to hook this modu...
def find_module(self, name, path=None):
if (name in self.loaded_modules): return None hooks = self.post_load_hooks.get(name, None) if hooks: return self
'If we get this far, then there are hooks waiting to be called on import of this module. We manually load the module and then run the hooks. @param name: The name of the module to import.'
def load_module(self, name):
self.loaded_modules.append(name) try: __import__(name, {}, {}, []) mod = sys.modules[name] self._run_hooks(name, mod) except: self.loaded_modules.pop() raise return mod
'@see: L{when_imported}'
def when_imported(self, name, *hooks):
if (name in sys.modules): for hook in hooks: hook(sys.modules[name]) return h = self.post_load_hooks.setdefault(name, []) h.extend(hooks)
'Run all hooks for a module.'
def _run_hooks(self, name, module):
hooks = self.post_load_hooks.pop(name, []) for hook in hooks: hook(module)
'@raise TypeError: Unable to coerce C{buf} to C{StringIO}.'
def __init__(self, buf=None):
self._buffer = StringIO() if isinstance(buf, python.str_types): self._buffer.write(buf) elif hasattr(buf, 'getvalue'): self._buffer.write(buf.getvalue()) elif (hasattr(buf, 'read') and hasattr(buf, 'seek') and hasattr(buf, 'tell')): old_pos = buf.tell() buf.seek(0) ...
'Get raw data from buffer.'
def getvalue(self):
return self._buffer.getvalue()
'Reads C{n} bytes from the stream.'
def read(self, n=(-1)):
if (n < (-1)): raise IOError('Cannot read backwards') bytes = self._buffer.read(n) return bytes
'Sets the file-pointer offset, measured from the beginning of this stream, at which the next write operation will occur. @param pos: @type pos: C{int} @param mode: @type mode: C{int}'
def seek(self, pos, mode=0):
return self._buffer.seek(pos, mode)
'Returns the position of the stream pointer.'
def tell(self):
return self._buffer.tell()
'Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int}'
def truncate(self, size=0):
if (size == 0): self._buffer = StringIO() self._len_changed = True return cur_pos = self.tell() self.seek(0) buf = self.read(size) self._buffer = StringIO() self._buffer.write(buf) self.seek(cur_pos) self._len_changed = True
'Writes the content of the specified C{s} into this buffer. @param s: Raw bytes'
def write(self, s, size=None):
self._buffer.write(s) self._len_changed = True
'Return total number of bytes in buffer.'
def _get_len(self):
if hasattr(self._buffer, 'len'): self._len = self._buffer.len return old_pos = self._buffer.tell() self._buffer.seek(0, 2) self._len = self._buffer.tell() self._buffer.seek(old_pos)
'Chops the tail off the stream starting at 0 and ending at C{tell()}. The stream pointer is set to 0 at the end of this function. @since: 0.4'
def consume(self):
try: bytes = self.read() except IOError: bytes = '' self.truncate() if (len(bytes) > 0): self.write(bytes) self.seek(0)
'Reads C{length} bytes from the stream. If an attempt to read past the end of the buffer is made, L{IOError} is raised.'
def _read(self, length):
bytes = self.read(length) if (len(bytes) != length): self.seek((0 - len(bytes)), 1) raise IOError(('Tried to read %d byte(s) from the stream' % length)) return bytes
'Whether the current endian is big endian.'
def _is_big_endian(self):
if (self.endian == DataTypeMixIn.ENDIAN_NATIVE): return (SYSTEM_ENDIAN == DataTypeMixIn.ENDIAN_BIG) return (self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK))
'Reads an C{unsigned char} from the stream.'
def read_uchar(self):
return ord(self._read(1))
'Writes an C{unsigned char} to the stream. @param c: Unsigned char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range.'
def write_uchar(self, c):
if (type(c) not in python.int_types): raise TypeError(('expected an int (got:%r)' % type(c))) if (not (0 <= c <= 255)): raise OverflowError(('Not in range, %d' % c)) self.write(struct.pack('B', c))
'Reads a C{char} from the stream.'
def read_char(self):
return struct.unpack('b', self._read(1))[0]
'Write a C{char} to the stream. @param c: char @type c: C{int} @raise TypeError: Unexpected type for int C{c}. @raise OverflowError: Not in range.'
def write_char(self, c):
if (type(c) not in python.int_types): raise TypeError(('expected an int (got:%r)' % type(c))) if (not ((-128) <= c <= 127)): raise OverflowError(('Not in range, %d' % c)) self.write(struct.pack('b', c))
'Reads a 2 byte unsigned integer from the stream.'
def read_ushort(self):
return struct.unpack(('%sH' % self.endian), self._read(2))[0]
'Writes a 2 byte unsigned integer to the stream. @param s: 2 byte unsigned integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range.'
def write_ushort(self, s):
if (type(s) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(s),))) if (not (0 <= s <= 65535)): raise OverflowError(('Not in range, %d' % s)) self.write(struct.pack(('%sH' % self.endian), s))
'Reads a 2 byte integer from the stream.'
def read_short(self):
return struct.unpack(('%sh' % self.endian), self._read(2))[0]
'Writes a 2 byte integer to the stream. @param s: 2 byte integer @type s: C{int} @raise TypeError: Unexpected type for int C{s}. @raise OverflowError: Not in range.'
def write_short(self, s):
if (type(s) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(s),))) if (not ((-32768) <= s <= 32767)): raise OverflowError(('Not in range, %d' % s)) self.write(struct.pack(('%sh' % self.endian), s))
'Reads a 4 byte unsigned integer from the stream.'
def read_ulong(self):
return struct.unpack(('%sL' % self.endian), self._read(4))[0]
'Writes a 4 byte unsigned integer to the stream. @param l: 4 byte unsigned integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range.'
def write_ulong(self, l):
if (type(l) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(l),))) if (not (0 <= l <= 4294967295)): raise OverflowError(('Not in range, %d' % l)) self.write(struct.pack(('%sL' % self.endian), l))
'Reads a 4 byte integer from the stream.'
def read_long(self):
return struct.unpack(('%sl' % self.endian), self._read(4))[0]
'Writes a 4 byte integer to the stream. @param l: 4 byte integer @type l: C{int} @raise TypeError: Unexpected type for int C{l}. @raise OverflowError: Not in range.'
def write_long(self, l):
if (type(l) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(l),))) if (not ((-2147483648) <= l <= 2147483647)): raise OverflowError(('Not in range, %d' % l)) self.write(struct.pack(('%sl' % self.endian), l))
'Reads a 24 bit unsigned integer from the stream. @since: 0.4'
def read_24bit_uint(self):
order = None if (not self._is_big_endian()): order = [0, 8, 16] else: order = [16, 8, 0] n = 0 for x in order: n += (self.read_uchar() << x) return n
'Writes a 24 bit unsigned integer to the stream. @since: 0.4 @param n: 24 bit unsigned integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range.'
def write_24bit_uint(self, n):
if (type(n) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(n),))) if (not (0 <= n <= 16777215)): raise OverflowError('n is out of range') order = None if (not self._is_big_endian()): order = [0, 8, 16] else: order = ...
'Reads a 24 bit integer from the stream. @since: 0.4'
def read_24bit_int(self):
n = self.read_24bit_uint() if ((n & 8388608) != 0): n -= 16777216 return n
'Writes a 24 bit integer to the stream. @since: 0.4 @param n: 24 bit integer @type n: C{int} @raise TypeError: Unexpected type for int C{n}. @raise OverflowError: Not in range.'
def write_24bit_int(self, n):
if (type(n) not in python.int_types): raise TypeError(('expected an int (got:%r)' % (type(n),))) if (not ((-8388608) <= n <= 8388607)): raise OverflowError('n is out of range') order = None if (not self._is_big_endian()): order = [0, 8, 16] else: ...
'Reads an 8 byte float from the stream.'
def read_double(self):
return struct.unpack(('%sd' % self.endian), self._read(8))[0]
'Writes an 8 byte float to the stream. @param d: 8 byte float @type d: C{float} @raise TypeError: Unexpected type for float C{d}.'
def write_double(self, d):
if (not (type(d) is float)): raise TypeError(('expected a float (got:%r)' % (type(d),))) self.write(struct.pack(('%sd' % self.endian), d))
'Reads a 4 byte float from the stream.'
def read_float(self):
return struct.unpack(('%sf' % self.endian), self._read(4))[0]
'Writes a 4 byte float to the stream. @param f: 4 byte float @type f: C{float} @raise TypeError: Unexpected type for float C{f}.'
def write_float(self, f):
if (type(f) is not float): raise TypeError(('expected a float (got:%r)' % (type(f),))) self.write(struct.pack(('%sf' % self.endian), f))
'Reads a UTF-8 string from the stream. @rtype: C{unicode}'
def read_utf8_string(self, length):
s = struct.unpack(('%s%ds' % (self.endian, length)), self.read(length))[0] return s.decode('utf-8')
'Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}.'
def write_utf8_string(self, u):
if (not isinstance(u, python.str_types)): raise TypeError(('Expected %r, got %r' % (python.str_types, u))) bytes = u if isinstance(bytes, unicode): bytes = u.encode('utf8') self.write(struct.pack(('%s%ds' % (self.endian, len(bytes))), bytes))
'@param buf: Initial byte stream. @type buf: C{str} or C{StringIO} instance @param min_buf_size: Ignored in the pure python version.'
def __init__(self, buf=None, min_buf_size=None):
StringIOProxy.__init__(self, buf=buf)
'Reads up to the specified number of bytes from the stream into the specified byte array of specified length. @raise IOError: Attempted to read past the end of the buffer.'
def read(self, length=(-1)):
if ((length == (-1)) and self.at_eof()): raise IOError('Attempted to read from the buffer but already at the end') elif ((length > 0) and ((self.tell() + length) > len(self))): raise IOError(('Attempted to read %d bytes from the buffer but ...
'Looks C{size} bytes ahead in the stream, returning what it finds, returning the stream pointer to its initial position. @param size: Default is 1. @type size: C{int} @raise ValueError: Trying to peek backwards. @return: Bytes.'
def peek(self, size=1):
if (size == (-1)): return self.peek((len(self) - self.tell())) if (size < (-1)): raise ValueError('Cannot peek backwards') bytes = '' pos = self.tell() while ((not self.at_eof()) and (len(bytes) != size)): bytes += self.read(1) self.seek(pos) return bytes
'Returns number of remaining bytes. @rtype: C{number} @return: Number of remaining bytes.'
def remaining(self):
return (len(self) - self.tell())
'Returns C{True} if the internal pointer is at the end of the stream. @rtype: C{bool}'
def at_eof(self):
return (self.tell() == len(self))
'Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to the stream. @type data: C{str} or C{unicode} @raise TypeError: data is not C{str} or C{unicode}'
def append(self, data):
t = self.tell() self.seek(0, 2) if hasattr(data, 'getvalue'): self.write_utf8_string(data.getvalue()) else: self.write_utf8_string(data) self.seek(t)
'Reads a ActionScript C{Number} value. In ActionScript 1 and 2 the C{NumberASTypes} type represents all numbers, both floats and integers. @rtype: C{int} or C{float}'
def readNumber(self):
return _check_for_int(self.stream.read_double())
'Reads a ActionScript C{Boolean} value. @rtype: C{bool} @return: Boolean.'
def readBoolean(self):
return bool(self.stream.read_uchar())
'Reads a C{string} from the stream. If bytes is C{True} then you will get the raw data read from the stream, otherwise a string that has been B{utf-8} decoded.'
def readString(self, bytes=False):
l = self.stream.read_ushort() b = self.stream.read(l) if bytes: return b return self.context.getStringForBytes(b)
'Reads a ActionScript C{null} value.'
def readNull(self):
return None
'Reads an ActionScript C{undefined} value. @return: L{Undefined<pyamf.Undefined>}'
def readUndefined(self):
return pyamf.Undefined
'Read mixed array. @rtype: L{pyamf.MixedArray}'
def readMixedArray(self):
self.stream.read_ulong() obj = pyamf.MixedArray() self.context.addObject(obj) attrs = self.readObjectAttributes(obj) for key in attrs.keys(): try: key = int(key) except ValueError: pass obj[key] = attrs[key] return obj
'Read a C{list} from the data stream.'
def readList(self):
obj = [] self.context.addObject(obj) l = self.stream.read_ulong() for i in xrange(l): obj.append(self.readElement()) return obj
'Reads an aliased ActionScript object from the stream and attempts to \'cast\' it into a python class. @see: L{pyamf.register_class}'
def readTypedObject(self):
class_alias = self.readString() try: alias = self.context.getClassAlias(class_alias) except pyamf.UnknownClassAlias: if self.strict: raise alias = pyamf.TypedObjectClassAlias(class_alias) obj = alias.createInstance(codec=self) self.context.addObject(obj) attrs...
'Read AMF3 elements from the data stream. @return: The AMF3 element read from the stream'
def readAMF3(self):
return self.context.getAMF3Decoder(self).readElement()
'Reads an anonymous object from the data stream. @rtype: L{ASObject<pyamf.ASObject>}'
def readObject(self):
obj = pyamf.ASObject() self.context.addObject(obj) obj.update(self.readObjectAttributes(obj)) return obj
'Reads a reference from the data stream. @raise pyamf.ReferenceError: Unknown reference.'
def readReference(self):
idx = self.stream.read_ushort() o = self.context.getObject(idx) if (o is None): raise pyamf.ReferenceError(('Unknown reference %d' % (idx,))) return o
'Reads a UTC date from the data stream. Client and servers are responsible for applying their own timezones. Date: C{0x0B T7 T6} .. C{T0 Z1 Z2 T7} to C{T0} form a 64 bit Big Endian number that specifies the number of nanoseconds that have passed since 1/1/1970 0:00 to the specified time. This format is UTC 1970. C{Z1} ...
def readDate(self):
ms = (self.stream.read_double() / 1000.0) self.stream.read_short() d = util.get_datetime(ms) if self.timezone_offset: d = (d + self.timezone_offset) self.context.addObject(d) return d
'Read UTF8 string.'
def readLongString(self):
l = self.stream.read_ulong() bytes = self.stream.read(l) return self.context.getStringForBytes(bytes)
'Read XML.'
def readXML(self):
data = self.readLongString() root = xml.fromstring(data) self.context.addObject(root) return root
'Writes the type to the stream. @type t: C{str} @param t: ActionScript type.'
def writeType(self, t):
self.stream.write(t)
'Writes the L{undefined<TYPE_UNDEFINED>} data type to the stream. @param data: Ignored, here for the sake of interface.'
def writeUndefined(self, data):
self.writeType(TYPE_UNDEFINED)
'Write null type to data stream.'
def writeNull(self, n):
self.writeType(TYPE_NULL)
'Write array to the stream. @param a: The array data to be encoded to the AMF0 data stream.'
def writeList(self, a):
if (self.writeReference(a) != (-1)): return self.context.addObject(a) self.writeType(TYPE_ARRAY) self.stream.write_ulong(len(a)) for data in a: self.writeElement(data)
'Write number to the data stream . @param n: The number data to be encoded to the AMF0 data stream.'
def writeNumber(self, n):
self.writeType(TYPE_NUMBER) self.stream.write_double(float(n))
'Write boolean to the data stream. @param b: The boolean data to be encoded to the AMF0 data stream.'
def writeBoolean(self, b):
self.writeType(TYPE_BOOL) if b: self.stream.write_uchar(1) else: self.stream.write_uchar(0)
'Similar to L{writeString} but does not encode a type byte.'
def serialiseString(self, s):
if (type(s) is unicode): s = self.context.getBytesForString(s) l = len(s) if (l > 65535): self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s)
'Write a string of bytes to the data stream.'
def writeBytes(self, s):
l = len(s) if (l > 65535): self.writeType(TYPE_LONGSTRING) else: self.writeType(TYPE_STRING) if (l > 65535): self.stream.write_ulong(l) else: self.stream.write_ushort(l) self.stream.write(s)
'Write a unicode to the data stream.'
def writeString(self, u):
s = self.context.getBytesForString(u) self.writeBytes(s)
'Write reference to the data stream. @param o: The reference data to be encoded to the AMF0 datastream.'
def writeReference(self, o):
idx = self.context.getObjectReference(o) if ((idx == (-1)) or (idx > 65535)): return (-1) self.writeType(TYPE_REFERENCE) self.stream.write_ushort(idx) return idx
'Write C{dict} to the data stream. @param o: The C{dict} data to be encoded to the AMF0 data stream.'
def _writeDict(self, o):
for (key, val) in o.iteritems(): if (type(key) in python.int_types): key = str(key) self.serialiseString(key) self.writeElement(val)
'Write mixed array to the data stream. @type o: L{pyamf.MixedArray}'
def writeMixedArray(self, o):
if (self.writeReference(o) != (-1)): return self.context.addObject(o) self.writeType(TYPE_MIXEDARRAY) try: max_index = max([y[0] for y in o.items() if isinstance(y[0], (int, long))]) if (max_index < 0): max_index = 0 except ValueError: max_index = 0 se...
'Write a Python object to the stream. @param o: The object data to be encoded to the AMF0 data stream.'
def writeObject(self, o):
if (self.writeReference(o) != (-1)): return self.context.addObject(o) alias = self.context.getClassAlias(o.__class__) alias.compile() if alias.amf3: self.writeAMF3(o) return if alias.anonymous: self.writeType(TYPE_OBJECT) else: self.writeType(TYPE_TYPE...
'Writes a date to the data stream. @type d: Instance of C{datetime.datetime} @param d: The date to be encoded to the AMF0 data stream.'
def writeDate(self, d):
if isinstance(d, datetime.time): raise pyamf.EncodeError(('A datetime.time instance was found but AMF0 has no way to encode time objects. Please use datetime.datetime instead (got:%r)' % (d,))) if (self.timezone_offset is not None): d -= self...
'Writes an XML instance.'
def writeXML(self, e):
self.writeType(TYPE_XML) data = xml.tostring(e) if isinstance(data, unicode): data = data.encode('utf-8') self.stream.write_ulong(len(data)) self.stream.write(data)
'Writes an element in L{AMF3<pyamf.amf3>} format.'
def writeAMF3(self, data):
self.writeType(TYPE_AMF3) self.context.getAMF3Encoder(self).writeElement(data)
'Construct a LineStyle. See class docstring for details on args.'
def __init__(self, width, on, off, color=None):
self.width = width self.on = on self.off = off self.color = color
'Add a new line to the chart. This is a convenience method which constructs the DataSeries and appends it for you. It returns the new series. points: List of equally-spaced y-values for the line label: Name of the line (used for the legend) color: Hex string, like \'ff0000\' for red pattern: Tuple for (length of ...
def AddLine(self, points, label=None, color=None, pattern=LineStyle.SOLID, width=LineStyle.THIN, markers=None):
if ((color is not None) and isinstance(color[0], common.Marker)): warnings.warn('Your code may be broken! You passed a list of Markers instead of a color. The old argument order (markers before color) is deprecated.', DeprecationWarning, s...
'DEPRECATED'
def AddSeries(self, points, color=None, style=LineStyle.solid, markers=None, label=None):
warnings.warn('LineChart.AddSeries is deprecated. Call AddLine instead. ', DeprecationWarning, stacklevel=2) return self.AddLine(points, color=color, width=style.width, pattern=(style.on, style.off), markers=markers, label=label)
'Get the URL for our graph. Args: use_html_entities: If True, reserved HTML characters (&, <, >, ") in the URL are replaced with HTML entities (&amp;, &lt;, etc.). Default is False.'
def Url(self, width, height, use_html_entities=False):
self._width = width self._height = height params = self._Params(self.chart) return util.EncodeUrl(self.url_base, params, self.escape_url, use_html_entities)
'Get an image tag for our graph.'
def Img(self, width, height):
url = self.Url(width, height, use_html_entities=True) tag = '<img src="%s" width="%s" height="%s" alt="chart"/>' return (tag % (url, width, height))
'Return the correct chart_type param for the chart.'
def _GetType(self, chart):
raise NotImplementedError
'Get a list of formatter functions to use for encoding.'
def _GetFormatters(self):
formatters = [self._GetLegendParams, self._GetDataSeriesParams, self._GetColors, self._GetAxisParams, self._GetGridParams, self._GetType, self._GetExtraParams, self._GetSizeParams] return formatters
'Collect all the different params we need for the URL. Collecting all params as a dict before converting to a URL makes testing easier.'
def _Params(self, chart):
chart = chart.GetFormattedChart() params = {} def Add(new_params): params.update(util.ShortenParameterNames(new_params)) for formatter in self.formatters: Add(formatter(chart)) for key in params: params[key] = str(params[key]) return params
'Get the size param.'
def _GetSizeParams(self, chart):
return {'size': ('%sx%s' % (int(self._width), int(self._height)))}
'Get any extra params (from extra_params).'
def _GetExtraParams(self, chart):
return self.extra_params
'Collect params related to the data series.'
def _GetDataSeriesParams(self, chart):
(y_min, y_max) = (chart.GetDependentAxis().min, chart.GetDependentAxis().max) series_data = [] markers = [] for (i, series) in enumerate(chart.data): data = series.data if (not data): continue series_data.append(data) for (x, marker) in series.markers: ...
'Color series color parameter.'
def _GetColors(self, chart):
colors = [] for series in chart.data: if (not series.data): continue colors.append(series.style.color) return util.JoinLists(color=colors)
'Get a class which can encode the data the way the user requested.'
def _GetDataEncoder(self, chart):
if (not self.enhanced_encoding): return util.SimpleDataEncoder() return util.EnhancedDataEncoder()