Tuesday, April 27, 2010

persistent_id of cPickle

    cPickle’s persistent_id must return a string in one line, or load will raise a truncated exception. So you can use base64.b64encode to encode your result in to one line string. Base64.encode returns multi-line result.

Sunday, April 25, 2010

Little tip of Mako template

    “selected” is always used to indicate selected state of option in SELECT HTML component. So it’s useful to write “selected” in one line as its option tag. Following code will generate this:

<%def name="optionselected(x)"><%if x: __M_writer(u"selected")%></%def>

<option value="python" ${optionselected(c.id == "python")}></option>

Confusion about amqplib properties

    Amqplib 0.6.1 introduces some properties when sending/receiving message in Message class. But when serializing “longstr” type properties, it did not use “utf-8”. So be careful to use its “application_headers” property, all keys in this diction will encode into “utf-8”, and values remain plain string.

Code snippets from amqplib 0.6.1:

def read_shortstr(self):
        """
        Read a utf-8 encoded string that's stored in up to
        255 bytes.  Return it decoded as a Python unicode object.

        """
        self.bitcount = self.bits = 0
        slen = unpack('B', self.input.read(1))[0]
        return self.input.read(slen).decode('utf-8')


    def read_longstr(self):
        """
        Read a string that's up to 2**32 bytes, the encoding
        isn't specified in the AMQP spec, so just return it as
        a plain Python string.

        """
        self.bitcount = self.bits = 0
        slen = unpack('>I', self.input.read(4))[0]
        return self.input.read(slen)