Exemplo n.º 1
0
  def serialize(cls, params, charset):
    return (None, repr(params))
  
  @classmethod
  def unserialize(cls, file, length=-1, charset=None):
    # return (list args, dict params)
    st = eval(file.read(length), {}, {})
    if isinstance(st, dict):
      return (None, st)
    elif isinstance(st, list):
      return (st, None)
    else:
      return ((st,), None)
  

serializers.register(PythonPySerializer)

if __name__ == '__main__':
  from datetime import datetime
  print PythonPySerializer.encode({
    'message': 'Hello worlds',
    'internets': [
      'interesting',
      'lolz',
      42.0,
      {
        'tubes': [1,3,16,18,24],
        'persons': True,
        'me again': {
          'message': 'Hello worlds',
          'internets': [
Exemplo n.º 2
0
            buf.append(u"\n%s" % indent)
            _encode_value(v, buf, level + 1)
            i += 1
        return buf


class PlainTextSerializer(Serializer):
    """Human-readable plain text"""

    name = "Plain text"
    extensions = ("txt",)
    media_types = ("text/plain",)
    charset = "utf-8"
    can_serialize = True

    if yaml:
        # If we have YAML-capabilities we use YAML for plain text output
        @classmethod
        def serialize(cls, params, charset):
            return YAMLSerializer.serialize(params, charset)

    else:

        @classmethod
        def serialize(cls, params, charset):
            s = u"%s\n" % u"".join(_encode_map(params, [])).strip()
            return (charset, s.encode(charset, cls.unicode_errors))


serializers.register(PlainTextSerializer)
Exemplo n.º 3
0
# encoding: utf-8
'''Example of a very simple "bare bones" text serializer
'''
from smisk.serialization import Serializer, serializers

class MyTextSerializer(Serializer):
  '''My simple text format
  '''
  # See the code in my_xml_serializer.py for explanation of the following
  # attributes:
  name = 'My text'
  extensions = ('mytext',)
  media_types = ('text/x-mytext',)
  charset = 'utf-8'
  can_serialize = True
  
  @classmethod
  def serialize(cls, params, charset):
    s = u'This is the response:\n'
    for kv in params.items():
      s += u'  %s: %s\n' % kv
    # This method must return a tuple of ( str<charset actually used>, str<data> )
    return (charset, s.encode(charset))
  

serializers.register(MyTextSerializer)
Exemplo n.º 4
0
Arquivo: json.py Projeto: rsms/smisk
  name = 'JSONP'
  extensions = ('js','jsonp')
  media_types = ('text/javascript',)
  
  @classmethod
  def serialize(cls, params, charset):
    callback = u'jsonp_callback'
    if request:
      callback = request.get.get('callback', callback)
    s = '%s(%s);' % (callback.encode(cls.charset), json_encode(params))
    return (cls.charset, s)
  

# Don't register if we did not find a json implementation
if json_encode is not None:
  serializers.register(JSONSerializer)
  serializers.register(JSONPSerializer)

if __name__ == '__main__':
  s = JSONSerializer.serialize({
    'message': 'Hello worlds',
    'internets': [
      'interesting',
      'lolz',
      42.0,
      {
        'tubes': [1,3,16,18,24],
        'persons': True,
        'me agåain': {
          'message': 'Hello worlds',
          'internets': [
Exemplo n.º 5
0
Arquivo: xhtml.py Projeto: rsms/smisk
          v = u''
      elif k == 'description':
        v = u''.join(encode_value(v, [], 'p'))
      else:
        v = xml_escape(unicode(v))
      xp[k] = v
    # Override if description_html is set
    if 'description_html' in params:
      xp['description'] = params['description_html']
    if 'traceback' not in xp:
      xp['traceback'] = ''
    s = ERROR_TEMPLATE % xp
    return (charset, s.encode(charset, cls.unicode_errors))
  

serializers.register(XHTMLSerializer)

ERROR_TEMPLATE = ur'''<?xml version="1.0" encoding="%(charset)s" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>%(name)s</title>
    <style type="text/css">
      body,html { padding:0; margin:0; background:#666; }
      h1 { padding:25pt 10pt 10pt 15pt; background:#ffb2bf; color:#560c00; font-family:arial,helvetica,sans-serif; margin:0; }
      address, p { font-family:'lucida grande',verdana,arial,sans-serif; }
      body > p, body > ul, body > ol { padding:10pt 16pt; background:#fff; color:#222; margin:0; font-size:.9em; }
      pre.traceback { padding:10pt 15pt 25pt 15pt; line-height:1.4; background:#f2f2ca; color:#52523b; margin:0; border-top:1px solid #e3e3ba; border-bottom:1px solid #555; }
      hr { display:none; }
      address { padding:10pt 15pt; color:#333; font-size:11px; }
    </style>
Exemplo n.º 6
0
    >>> print pickle.load(urllib.urlopen("http://localhost:8080/.pickle?hello=123"))
  '''
  name = 'Python pickle'
  extensions = ('pickle',)
  media_types = ('application/x-python-pickle', 'application/x-pickle')
  can_serialize = True
  can_unserialize = True
  
  @classmethod
  def serialize(cls, params, charset=None):
    return (None, dumps(params, HIGHEST_PROTOCOL))
  
  @classmethod
  def unserialize(cls, file, length=-1, charset=None):
    # return (list args, dict params)
    if length == 0:
      return (None, None)
    elif length > 0 and length < 1024:
      st = loads(file.read(length))
    else:
      st = load(file)
    if isinstance(st, dict):
      return (None, st)
    elif isinstance(st, list):
      return (st, None)
    else:
      return ((st,), None)
  

serializers.register(PythonPickleSerializer)
Exemplo n.º 7
0
    # return (collection args, dict params)
    s = file.read(length)
    if charset:
      s = s.decode(charset, cls.unicode_errors)
    st = yaml.load(s, Loader=Loader)
    if isinstance(st, dict):
      return (None, st)
    elif isinstance(st, list):
      return (st, None)
    else:
      return ((st,), None)
  

# Register if we have a backing YAML implementation
if yaml is not None:
  serializers.register(YAMLSerializer)
  
  # support for serializing Entities:
  from smisk.mvc.model import Entity
  def entity_serializer(dumper, entity):
    return dumper.represent_data(entity.to_dict())
  
  log.debug('registering smisk.mvc.model.Entity YAML serializer (W)')
  Dumper.add_multi_representer(Entity, entity_serializer)
  
  # support for serializing data:
  def data_serializer(dumper, dat):
    return dumper.represent_scalar(u'!data', dat.encode())
  
  def data_unserializer(loader, datatype, node):
    return opaque_data.decode(node.value)
Exemplo n.º 8
0
Arquivo: xmlrpc.py Projeto: rsms/smisk
  @classmethod
  def serialize_error(cls, status, params, charset=None):
    msg = u'%s: %s' % (params['name'], params['description'])
    return (charset, dumps(Fault(params['code'], msg), encoding=charset))
  
  @classmethod
  def unserialize(cls, file, length=-1, encoding=None):
    # return (list args, dict params)
    params, method_name = loads(file.read(length))
    
    # Override request path with mathodName. i.e. method.name -> /method/name
    if cls.respect_method_name:
      if method_name is None:
        raise http.InternalServerError(
          'respect_method_name is enabled but request did not include methodName')
      Application.current.request.url.path = '/'+'/'.join(method_name.split('.'))
    
    args = []
    kwargs = {}
    if len(params) > 0:
      for o in params:
        if isinstance(o, dict):
          kwargs.update(o)
        else:
          args.append(o)
    
    return (args, kwargs)
  

serializers.register(XMLRPCSerializer)