def encode(self, **kwargs): """ Encode the transport into a json string and return X-JSON """ if self.__fetch_arg__(kwargs, 'x_header', True): self.controller.content_type = 'application/x-json' self.controller.env.headers.append(('X-JSON', json.encode(self.strip()))) return '<X-JSON Object>' else: self.controller.content_type = 'text/plain' return json.encode(self.strip())
def test_decode_by_json(self): encoded = json.encode(self.col) decoded = json.decode(encoded) self.assertEquals(decoded['age'], self.col.age) self.assertEquals(decoded['location'], self.col.location) self.assertEquals(decoded['name'], self.col.name) self.assertEquals(type(decoded), type({}))
def producer(self, client): chars_left = 1 msg = [""] msg_length = None # Consume the message while chars_left > 0: chunk = client.recv(chars_left) # Check if the client closed prematurely if chunk == "": print "ERROR: Client socket closed prematurely" break # Look for the message size if msg_length is None: if chunk == ":": try: msg_length = int(msg.pop()) chars_left = msg_length continue except ValueError: client.sendall("BAD") break else: msg[0] += chunk else: # Once size is known, the rest is the actual message if chars_left > 1: chars_left -= len(chunk) msg.append(chunk) # Combine the chunks msg = "".join(msg) # Check to see if this is a message result fetch if msg.endswith(".msg"): result = self.queue.fetch(msg) result = json.encode(result) client.sendall(result) client.shutdown(0) client.close() return # Decode and add to the queue try: msg = message.Message.decode(msg) msg = message.MessageFactory(msg) self.queue.add(msg) print "%s added" % msg.name # Send a response to the client client.sendall(msg.name) except message.InvalidMessageEncodingError, er: print "Bad message body" client.sendall("BAD")
def encode(self): try: mask = '%Y/%m/%d %H:%M:%S' self.created = self.created.strftime(mask) if not self.updated is None: self.updated = self.created.updated(mask) return json.encode(self) except TypeError, er: msg = 'Message is not [json] not encodable: ' + str(self) raise TypeError(msg)
def encode(self, **kwargs): """ Encode the transport into a json string and return X-JSON """ indent = self.__default__(self.controller, kwargs, 'indent', None) if indent: try: indent = int(indent) except: pass if self.__default__(self.controller, kwargs, 'x_header', False): self.controller.content_type = 'application/x-json' self.controller.env.headers.append(('X-JSON', json.encode(self.strip(), indent=indent))) return '<X-JSON Object>' else: self.controller.content_type = 'text/plain' return json.encode(self.strip(), indent=indent)
def persist_db(self): """ Persist the session state to the database. This method will call _gc() to garbage collect the session specific database connection if it exists. """ # Keep track of what happens waspersisted = False # Indicate a successfull db persist [rollback if necessary] current_stale_count = self[stale_count] self[stale_count] = 0 # Prepare the sql sql = "SELECT session_set(%s, %s, TRUE);" sql = sql % (db.cstr(self._guid), db.cstr(json.encode(self))) # Attempt the persist try: self.connect_db() self._cursor.execute(sql) self._conn.commit() waspersisted = True except: try: self._conn.rollback() except: pass self.flush_next_persist() self[stale_count] = current_stale_count finally: # Because persistance is always at the end of the process # flow (actually called by apache.handler) we can safely # close the database connection now, this is the last db # work to be done. self._gc() # If the db persist failed for whatever reason, try to # failover on the cache till it comes back up. if not waspersisted: if self.persist_cache(): waspersisted = True # Raise if we can't persist if not waspersisted: raise error.SessionUnableToPersistError()
def encode(self, data): """ Encode the session using the specified transport (cPickle by default). @param data: Session data to be encoded @type data: Instance of chula.session.Session object @return: str """ if self._transport == CPICKLE: # Since cPickle actually pickles the entire object we need # to exclude all of the private variables prior to encoding: return cPickle.dumps(dict(self)) else: return json.encode(data)
def persist_cache(self): """ Persist the session state to cache """ if self._timeout > 0: timeout = self._timeout else: # Set a reasonable default for cookies lacking an expiration timeout = 30 if isinstance(self._cache, memcache.Client): result = self._cache.set(self.mkey(), json.encode(self), timeout * 60) # Non zero status is success if result != 0: return True return False
def receive_message(self, client): """ Receive a message from a chula.queue.client or anything else really. @param client: TCP Socket @type client: socket._socketobject """ chars_left = 1 msg = [''] msg_length = None # Consume the message while chars_left > 0: chunk = client.recv(chars_left) # Check if the client closed prematurely if chunk == '': print 'ERROR: Client socket closed prematurely' break # Look for the message size if msg_length is None: if chunk == ':': try: msg_length = int(msg.pop()) chars_left = msg_length continue except ValueError: client.sendall('BAD') break else: msg[0] += chunk else: # Once size is known, the rest is the actual message if chars_left > 1: chars_left -= len(chunk) msg.append(chunk) # Combine the chunks msg = ''.join(msg) # Check to see if this is a message result fetch if msg.endswith('.msg'): result = self.queue.fetch(msg) result = json.encode(result) client.sendall(result) client.shutdown(0) client.close() return # Decode and add to the queue try: msg = message.Message.decode(msg) msg = message.MessageFactory(msg) self.queue.add(msg) print '%s added' % msg.name # Send a response to the client client.sendall(msg.name) except message.InvalidMessageEncodingError, er: print 'Bad message body' client.sendall('BAD')
def test_json_encoding(self): encoded = json.encode(self.human) decoded = json.decode(encoded) self.assertEquals(decoded['foot'], self.human.foot) self.assertEquals(decoded['head'], self.human.head)
def test_encode_by_json(self): encoded = json.encode(self.col) self.assertEquals(type(encoded), type('string'))