Ejemplo n.º 1
0
	def test_with_date(self):
		"""
		Should convert dates to ISO format when serializing
		"""
		obj = {
			'where': 'My House',
			'when': datetime(2014, 9, 5, 9, 23),
			'another_thing': {
				'foo': 23,
				'bar': [1,2,3]
			}
		}
		serializer = MsgPackSerializer()
		stream = StringIO( serializer.serialize(obj) )
		unserialized_obj = serializer.unserialize(stream)
		self.assertEquals(unserialized_obj,
			{
				'where': 'My House',
				'when': '2014-09-05T09:23:00',
				'another_thing': {
					'foo': 23,
					'bar': [1,2,3]
				}
			}
		)
Ejemplo n.º 2
0
    def test_simple(self):
        """
		Should convert simple structures to and from JSON
		"""
        obj = {'foo': 'bar'}
        serializer = MsgPackSerializer()
        packed_data = serializer.serialize(obj)
        msgpack.unpackb(packed_data)
        stream = StringIO(packed_data)
        unserialized_obj = serializer.unserialize(stream)
        self.assertEquals(unserialized_obj, obj)
	def test_simple(self):
		"""
		Should convert simple structures to and from JSON
		"""
		obj = {'foo':'bar'}
		serializer = MsgPackSerializer()
		packed_data = serializer.serialize(obj)
		msgpack.unpackb(packed_data)
		stream = StringIO( packed_data )
		unserialized_obj = serializer.unserialize(stream)
		self.assertEquals(unserialized_obj, obj)
Ejemplo n.º 4
0
	def test_fail(self):
		"""
		Should raise an exception when trying to serialize other things
		"""
		class Foo(object):
			pass
			
		value = {'foo':Foo()}
		serializer = MsgPackSerializer()
		
		with self.assertRaises(Exception):
			serializer.serialize(obj)
Ejemplo n.º 5
0
    def test_iterables(self):
        """
		Should serialize any iterable
		"""
        def foo():
            for i in range(0, 5):
                yield i

        obj = {'foo': foo()}
        serializer = MsgPackSerializer()
        stream = StringIO(serializer.serialize(obj))
        unserialized_obj = serializer.unserialize(stream)
        self.assertEquals(unserialized_obj, {'foo': [0, 1, 2, 3, 4]})
	def test_iterables(self):
		"""
		Should serialize any iterable
		"""
		def foo():
			for i in range(0,5):
				yield i
				
		obj = {'foo':foo()}
		serializer = MsgPackSerializer()
		stream = StringIO( serializer.serialize(obj) )
		unserialized_obj = serializer.unserialize(stream)
		self.assertEquals(unserialized_obj, {'foo': [0,1,2,3,4]})
Ejemplo n.º 7
0
class EntityResource(Resource):

    accept_serializers = (JSONSerializer(), MsgPackSerializer())

    def __init__(self, interface, views):
        self.interface = interface
        self.views = views
        self.logger = logging.getLogger(__name__)

    def get(self, id):
        if id:
            kwargs = self.parse_params('show_hidden', 'context', 'embedded')
            item = self.interface.get(id, **kwargs)
            return self.response(item)
        else:
            kwargs = self.parse_params()
            items = self.interface.list(**kwargs)
            return self.response(items)

    def head(self):
        kwargs = self.parse_params()
        kwargs['count'] = True
        count = self.interface.list(**kwargs)
        res = make_response('')
        res.headers['Content-Type'], _ = View.choose(
            request.headers.get('accept'), self.views)
        res.headers['X-Count'] = str(count)
        return res

    def post(self):
        fields = self.get_fields_from_request()
        kwargs = self.parse_params('show_hidden', 'context', 'embedded')
        try:
            item = self.interface.create(fields, **kwargs)
        except errors.CompoundValidationError, e:
            return self.response(e.errors, status_code=400)
        return self.response(item, status_code=201)
Ejemplo n.º 8
0
class Resource(object):
    """
	A resource exposes an interface through falcon
	"""

    # The types of content that are accepted.
    accept_serializers = (JSONSerializer(), MsgPackSerializer())

    def __init__(self, interface, views):
        self.interface = interface
        self.views = views
        self.logger = logging.getLogger(__name__)

    def add_to_falcon(self, app):
        methods = self.interface.rules.enabled_methods
        interface_methods = methods.intersection((LIST, CREATE))
        individual_methods = methods.intersection(
            (GET, REPLACE, UPDATE, DELETE))

        if not interface_methods and not individual_methods:
            raise Exception, "The '%s' interface exposes no methods" % self.interface.plural_name

        if interface_methods:
            app.add_route('/%s' % self.interface.plural_name,
                          ListEndpoint(self, interface_methods))

        if individual_methods:
            app.add_route('/%s/{id}' % self.interface.plural_name,
                          IndividualEndpoint(self, individual_methods))

        for link_name, link in self.interface.entity.get_links().items():
            if self.interface.api.get_interface_for_entity(link.entity):
                app.add_route(
                    '/%s/{id}/%s' % (self.interface.plural_name, link_name),
                    ReferenceEndpoint(self, link_name))

    def list(self, req, resp):
        kwargs = self.parse_params(req)
        items = self.interface.list(**kwargs)
        self.send_list(req, resp, items)

    def count(self, req, resp):
        kwargs = self.parse_params(req)
        kwargs['count'] = True
        result = self.interface.list(**kwargs)
        resp.content_type, _ = View.choose(req.get_header('accept'),
                                           self.views)
        resp.set_header('X-Count', str(result))

    def create(self, req, resp):
        fields = self.get_fields_from_request(req)
        kwargs = self.parse_params(req, 'show_hidden', 'context', 'embedded')
        item = self.interface.create(fields, **kwargs)
        resp.status = falcon.HTTP_201
        self.send_one(req, resp, item)

    def get(self, req, resp, id):
        kwargs = self.parse_params(req, 'show_hidden', 'context', 'embedded')
        item = self.interface.get(id, **kwargs)
        self.send_one(req, resp, item)

    def update(self, req, resp, id):
        fields = self.get_fields_from_request(req)
        kwargs = self.parse_params(req, 'show_hidden', 'context', 'embedded')
        item = self.interface.update(id, fields, **kwargs)
        self.send_one(req, resp, item)

    def replace(self, req, resp, id):
        fields = self.get_fields_from_request(req)
        kwargs = self.parse_params(req, 'show_hidden', 'context', 'embedded')
        item = self.interface.replace(id, fields, **kwargs)
        self.send_one(req, resp, item)

    def delete(self, req, resp, id):
        self.interface.delete(id, context=get_context(req.env))

    def get_link_or_reference(self, req, resp, id, link_name):
        kwargs = self.parse_params(req)
        result = self.interface.link(id, link_name, **kwargs)
        if isinstance(result, dict):
            self.send_one(req, resp, result)
        else:
            self.send_list(req, resp, result)

    def count_link_or_reference(self, req, resp, id, link_name):
        kwargs = self.parse_params(req)
        kwargs['count'] = True
        result = self.interface.link(id, link_name, **kwargs)
        resp.content_type, _ = View.choose(req.get_header('accept'),
                                           self.views)
        if isinstance(result, int):
            resp.set_header('X-Count', str(result))

    def send_one(self, req, resp, item):
        resp.content_type, resp.body = self.serialize_one(req, item)

    def send_list(self, req, resp, items):
        resp.content_type, resp.body = self.serialize_list(req, items)

    def serialize_one(self, req, data):
        return self.serialize(req, 'get_individual_response', data)

    def serialize_list(self, req, data):
        return self.serialize(req, 'get_list_response', data)

    def serialize(self, req, method_name, data):
        view = self.get_view(req)
        method = getattr(view, method_name)
        try:
            return method(req.get_header('accept'), data)
        except Exception, e:
            self.logger.exception('Failed to serialize response.')
            raise falcon.HTTPInternalServerError('Internal Server Error', '')