Esempio n. 1
0
class MyDefaultMapperResource_1(Resource):
    """ Define a mapper and a default mapper. """
    mapper = JsonMapper()

    # this won't be used
    default_mapper = XmlMapper()

    def get(self, request):
        return {'key': 'löyhkä'}
Esempio n. 2
0
class PersonResource(Resource):
    """ Person resource. """
    default_mapper = JsonMapper()
    representation = representations.Person()

    def get(self, request):
        people = models.Person.objects.all()
        return [{'id': person.pk, 'name': person.name, 'age': person.age} \
                for person in people]

    def post(self, data, request):
        person = self.representation.__class__(data)
        person.save()
        return Response(201, None, {
            'Location':
            '%s/%s' % (reverse('validation'), person.instance.pk)
        })
Esempio n. 3
0
def register_mappers():
    textmapper = datamapper.DataMapper()
    jsonmapper = JsonMapper()
    xmlmapper = XmlMapper(numbermode='basic')

    # we'll be tolerant on what we receive
    # remember to put these false content types in the beginning so that they
    # are overridden by the proper ones
    datamapper.manager.register_mapper(jsonmapper, 'application/x-javascript', 'json')
    datamapper.manager.register_mapper(jsonmapper, 'text/javascript', 'json')
    datamapper.manager.register_mapper(jsonmapper, 'text/x-javascript', 'json')
    datamapper.manager.register_mapper(jsonmapper, 'text/x-json', 'json')

    # text mapper
    datamapper.manager.register_mapper(textmapper, 'text/plain', 'text')

    # xml mapper
    datamapper.manager.register_mapper(xmlmapper, 'text/xml', 'xml')

    # json mapper
    datamapper.manager.register_mapper(jsonmapper, 'application/json', 'json')
Esempio n. 4
0
class MyDefaultMapperResource_2(Resource):
    """ Define default mapper. """
    default_mapper = JsonMapper()

    def get(self, request):
        return {'key': 'löyhkä'}
Esempio n. 5
0
 def test_format_scandic_json(self):
     m = JsonMapper()
     data = {'key': 'lähtö'}
     resp = m.format(data)
     self.assertEquals(resp['Content-Type'], 'application/json; charset=utf-8')
     self.assertEquals(resp.content, '{\n    "key": "lähtö"\n}')
Esempio n. 6
0
 def test_parse_scandic_json(self):
     m = JsonMapper()
     result = m.parse('{"key": "lähtö"}', 'utf-8')
     self.assertTrue(isinstance (result['key'], unicode))
Esempio n. 7
0
class User(Resource):

    # if client doesn't specify mimetype, assume JSON
    default_mapper = JsonMapper()

    def post(self, data, request, id):
        """ Create a new resource using POST """
        if id:
            # can't post to individual user
            raise errors.MethodNotAllowed()
        user = self._dict_to_model(data)
        user.save()
        # according to REST, return 201 and Location header
        return Response(201, None,
                        {'Location': '%s%d' % (reverse('user'), user.pk)})

    def get(self, request, id):
        """ Get one user or all users """
        if id:
            return self._get_one(id)
        else:
            return self._get_all()

    def put(self, data, request, id):
        """ Update a single user. """
        if not id:
            # can't update the whole container
            raise errors.MethodNotAllowed()
        userdata = self._dict_to_model(data)
        userdata.pk = id
        try:
            userdata.save(force_update=True)
        except DatabaseError:
            # can't udpate non-existing user
            raise errors.NotFound()

    def delete(self, request, id):
        """ Delete a single user. """
        if not id:
            # can't delete the whole container
            raise errors.MethodNotAllowed()
        try:
            models.User.objects.get(pk=id).delete()
        except models.User.DoesNotExist:
            # we never had it, so it's definitely deleted
            pass

    def _get_one(self, id):
        """ Get one user from db and turn into dict """
        try:
            return self._to_dict(models.User.objects.get(pk=id))
        except models.User.DoesNotExist:
            raise errors.NotFound()

    def _get_all(self):
        """ Get all users from db and turn into list of dicts """
        return [self._to_dict(row) for row in models.User.objects.all()]

    def _to_dict(self, row):
        """ Convert a single user db row into dict. """
        return {
            'name': row.name,
            'age': row.age,
        }

    def _dict_to_model(self, data):
        """ Create new user model instance based on the received data.

        Note that the created user is not saved into database.
        """

        try:
            # we can do this because we have same fields
            # in the representation and in the model:
            user = models.User(**data)
        except TypeError:
            # client sent bad data
            raise errors.BadRequest()
        else:
            return user