Exemple #1
0
def upload_photo():
    """
    Upload a photo, bypassing the API for cleaner invocation.
    """
    data = request.form

    # Create a new photo.
    photo = {
        'credit': data.get('credit', ''),
        'caption': data.get('caption', ''),
        'file_name': data.get('file_name', ''),
    }
    photo = models.Photo(**photo)

    # Get the data.
    if data.get('file_string', None):
        photo.write_photo(data['file_string'])

    # Do the save.
    photo.save()

    # Return data.
    serializer = Serializer()
    data = serializer.serialize_object(photo)
    return jsonify(data)
Exemple #2
0
def upload_photo():
    """
    Upload a photo, bypassing the API for cleaner invocation.
    """
    data = request.form

    # Create a new photo.
    photo = {
        'credit': data.get('credit', ''),
        'caption': data.get('caption', ''),
        'file_name': data.get('file_name', ''),
    }
    photo = models.Photo(**photo)

    # Get the data.
    if data.get('file_string', None):
        photo.write_photo(data['file_string'])

    # Do the save.
    photo.save()

    # Return data.
    serializer = Serializer()
    data = serializer.serialize_object(photo)
    return jsonify(data)
Exemple #3
0
 def __jsonify__(self, *extra_fields):
     """Serialize model to JSON that can be viewed by client. Used by jsonify()
     """
     safe_fields = ['id', 'service', 'profile'] + list(extra_fields)
     safe_fields = [field for field in safe_fields if hasattr(self, field)]
     s = Serializer()
     return s.serialize_object(self, fields={self.__class__: safe_fields})
Exemple #4
0
 def __jsonify__(self, *extra_fields):
     """Serialize model to JSON that can be viewed by client. Used by
     halo.endpoints.util.jsonify().
     """
     extra_fields = [field for field in safe_fields if hasattr(self, field)]
     s = Serializer()
     return s.serialize_object(self, fields={self.__class__: extra_fields})
Exemple #5
0
    def json_response(self, filename='export.json'):
        serializer = Serializer()
        prepared_query = self.prepare_query()
        field_dict = {}
        for field in prepared_query._select:
            field_dict.setdefault(field.model, [])
            field_dict[field.model].append(field.name)

        def generate():
            i = prepared_query.count()
            yield b'[\n'
            for obj in prepared_query:
                i -= 1
                obj_data = serializer.serialize_object(obj, field_dict)
                yield json.dumps(obj_data).encode('utf-8')
                if i > 0:
                    yield b',\n'
            yield b'\n]'

        headers = Headers()
        headers.add('Content-Type', 'application/javascript')
        headers.add('Content-Disposition',
                    'attachment; filename=%s' % filename)
        return Response(generate(),
                        mimetype='text/javascript',
                        headers=headers,
                        direct_passthrough=True)
Exemple #6
0
def update_photo_credit():
    """
    Update a photo, bypassing the API for cleaner invocation.
    """
    data = request.form

    # Get the photo.
    photo = models.Photo.get(models.Photo.id == int(data['id']))
    photo.credit = data.get('credit', None)

    # Do the save.
    photo.save()

    # Return data.
    serializer = Serializer()
    data = serializer.serialize_object(photo)
    return jsonify(data)
Exemple #7
0
def update_photo_credit():
    """
    Update a photo, bypassing the API for cleaner invocation.
    """
    data = request.form

    # Get the photo.
    photo = models.Photo.get(models.Photo.id == int(data['id']))
    photo.credit = data.get('credit', None)

    # Do the save.
    photo.save()

    # Return data.
    serializer = Serializer()
    data = serializer.serialize_object(photo)
    return jsonify(data)
Exemple #8
0
 def serialize_models(self, obj):
     """Serialize object to dictionary if db model. Recurses dictionaries
     """
     if isinstance(obj, Model):
         return Serializer().serialize_object(obj)
     elif isinstance(obj, dict):
         return dict((key, self.serialize_models(value)) \
                      for key, value in obj.iteritems())
     else:
         return obj
Exemple #9
0
def upload_audio():
    """
    Upload some audio, bypassing the API for cleaner invocation.
    """
    data = request.form

    audio = {
        'credit': data.get('credit', ''),
        'caption': data.get('caption', ''),
        'file_name': data.get('file_name', ''),
    }

    # Create the model
    audio = models.Audio(**audio)
    audio.process_audio(data['file_string'])

    audio.save()

    serializer = Serializer()
    data = serializer.serialize_object(audio)

    return jsonify(data)
Exemple #10
0
def upload_audio():
    """
    Upload some audio, bypassing the API for cleaner invocation.
    """
    data = request.form

    audio = {
        'credit': data.get('credit', ''),
        'caption': data.get('caption', ''),
        'file_name': data.get('file_name', ''),
    }

    # Create the model
    audio = models.Audio(**audio)
    audio.process_audio(data['file_string'])

    audio.save()

    serializer = Serializer()
    data = serializer.serialize_object(audio)

    return jsonify(data)
Exemple #11
0
    def json_response(self, filename='export.json'):
        serializer = Serializer()
        prepared_query = self.prepare_query()

        def generate():
            i = prepared_query.count()
            yield '[\n'
            for obj in prepared_query:
                i -= 1
                yield json.dumps(serializer.serialize_object(obj, prepared_query.query))
                if i > 0:
                    yield ',\n'
            yield '\n]'
        headers = Headers()
        headers.add('Content-Type', 'application/javascript')
        headers.add('Content-Disposition', 'attachment; filename=%s' % filename)
        return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def serialize():
    user = auth.get_logged_in_user()
    myresource = resource.fetch_by_user(user)
    return json.dumps(Serializer().serialize_object(myresource))
 def setUp(self):
     super(SerializerTestCase, self).setUp()
     self.s = Serializer()
     self.d = Deserializer()
class SerializerTestCase(FlaskPeeweeTestCase):
    def setUp(self):
        super(SerializerTestCase, self).setUp()
        self.s = Serializer()
        self.d = Deserializer()

    def test_serializer(self):
        users = self.create_users()
        serialized = self.s.serialize_object(self.admin)
        self.assertEqual(
            serialized, {
                'id': self.admin.id,
                'username': '******',
                'password': self.admin.password,
                'join_date':
                self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
                'active': True,
                'admin': True,
                'email': '',
            })

        serialized = self.s.serialize_object(self.admin,
                                             fields={User: ['id', 'username']})
        self.assertEqual(serialized, {
            'id': self.admin.id,
            'username': '******',
        })

        serialized = self.s.serialize_object(
            self.admin, exclude={User: ['password', 'join_date']})
        self.assertEqual(
            serialized, {
                'id': self.admin.id,
                'username': '******',
                'active': True,
                'admin': True,
                'email': '',
            })

    def test_deserializer(self):
        users = self.create_users()

        deserialized, models = self.d.deserialize_object(
            User(), {
                'id': self.admin.id,
                'username': '******',
                'password': self.admin.password,
                'join_date':
                self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
                'active': True,
                'admin': True,
            })

        for attr in ['id', 'username', 'password', 'active', 'admin']:
            self.assertEqual(
                getattr(deserialized, attr),
                getattr(self.admin, attr),
            )

        self.assertEqual(
            deserialized.join_date.strftime('%Y-%m-%d %H:%M:%S'),
            self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
        )

        admin_pk = self.admin.id

        deserialized, models = self.d.deserialize_object(
            self.admin, {
                'username': '******',
                'active': False,
                'admin': False,
            })

        self.assertEqual(deserialized.username, 'edited')
        self.assertEqual(deserialized.admin, False)
        self.assertEqual(deserialized.active, False)
        self.assertEqual(deserialized.id, admin_pk)

        deserialized.save()

        self.assertEqual(User.select().count(), 3)
        edited = User.get(username='******')
        self.assertEqual(edited.id, admin_pk)

    def test_s_and_d(self):
        self.create_users()

        s = self.s.serialize_object(self.admin)
        d, model_list = self.d.deserialize_object(User(), s)
        self.assertEqual(d, self.admin)
class SerializerTestCase(FlaskPeeweeTestCase):
    def setUp(self):
        super(SerializerTestCase, self).setUp()
        self.s = Serializer()
        self.ms = ModelSerializer()
        self.d = Deserializer()
        self.md = ModelDeserializer()

    def test_serializer(self):
        users = self.create_users()
        serialized = self.s.serialize_object(self.admin)
        self.assertEqual(
            serialized,
            {
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
                "email": "",
            },
        )

        serialized = self.s.serialize_object(self.admin, fields=("id", "username"))
        self.assertEqual(serialized, {"id": self.admin.id, "username": "******"})

        serialized = self.s.serialize_object(self.admin, exclude=("password", "join_date"))
        self.assertEqual(
            serialized, {"id": self.admin.id, "username": "******", "active": True, "admin": True, "email": ""}
        )

    def test_deserializer(self):
        users = self.create_users()

        deserialized = self.d.deserialize_object(
            {
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
            },
            User(),
        )

        for attr in ["id", "username", "password", "active", "admin"]:
            self.assertEqual(getattr(deserialized, attr), getattr(self.admin, attr))

        self.assertEqual(
            deserialized.join_date.strftime("%Y-%m-%d %H:%M:%S"), self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S")
        )

        admin_pk = self.admin.id

        deserialized = self.d.deserialize_object({"username": "******", "active": False, "admin": False}, self.admin)

        self.assertEqual(deserialized.username, "edited")
        self.assertEqual(deserialized.admin, False)
        self.assertEqual(deserialized.active, False)
        self.assertEqual(deserialized.id, admin_pk)

        deserialized.save()

        self.assertEqual(User.select().count(), 3)
        edited = User.get(username="******")
        self.assertEqual(edited.id, admin_pk)

    def test_model_serializer(self):
        users = self.create_users()
        serialized = self.ms.serialize_object(self.admin)
        self.assertEqual(
            serialized,
            {
                "__model__": "User",
                "__module__": "flask_peewee.tests.test_app",
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
                "email": "",
            },
        )

        serialized = self.ms.serialize_object(self.admin, fields=("id", "username"))
        self.assertEqual(
            serialized,
            {
                "__model__": "User",
                "__module__": "flask_peewee.tests.test_app",
                "id": self.admin.id,
                "username": "******",
            },
        )

    def test_model_deserializer(self):
        users = self.create_users()

        deserialized = self.md.deserialize_object(
            {
                "__model__": "User",
                "__module__": "flask_peewee.tests.test_app",
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
            }
        )

        for attr in ["id", "username", "password", "active", "admin"]:
            self.assertEqual(getattr(deserialized, attr), getattr(self.admin, attr))

        self.assertEqual(
            deserialized.join_date.strftime("%Y-%m-%d %H:%M:%S"), self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S")
        )

        admin_pk = self.admin.id

        deserialized = self.md.deserialize_object(
            {
                "__model__": "User",
                "__module__": "flask_peewee.tests.test_app",
                "username": "******",
                "active": False,
                "admin": False,
            },
            self.admin,
        )

        self.assertEqual(deserialized.username, "edited")
        self.assertEqual(deserialized.admin, False)
        self.assertEqual(deserialized.active, False)
        self.assertEqual(deserialized.id, admin_pk)

        deserialized.save()

        self.assertEqual(User.select().count(), 3)
        edited = User.get(username="******")
        self.assertEqual(edited.id, admin_pk)

    def test_s_and_d(self):
        self.create_users()

        s = self.s.serialize_object(self.admin)
        d = self.d.deserialize_object(s, User())
        self.assertEqual(d, self.admin)

        s = self.ms.serialize_object(self.admin)
        d = self.md.deserialize_object(s)
        self.assertEqual(d, self.admin)
Exemple #16
0
 def setUp(self):
     super(SerializerTestCase, self).setUp()
     self.s = Serializer()
     self.d = Deserializer()
Exemple #17
0
class SerializerTestCase(FlaskPeeweeTestCase):
    def setUp(self):
        super(SerializerTestCase, self).setUp()
        self.s = Serializer()
        self.d = Deserializer()
    
    def test_serializer(self):
        users = self.create_users()
        serialized = self.s.serialize_object(self.admin)
        self.assertEqual(serialized, {
            'id': self.admin.id,
            'username': '******',
            'password': self.admin.password,
            'join_date': self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
            'active': True,
            'admin': True,
            'email': '',
        })
        
        serialized = self.s.serialize_object(self.admin, fields={User: ['id', 'username']})
        self.assertEqual(serialized, {
            'id': self.admin.id,
            'username': '******',
        })
        
        serialized = self.s.serialize_object(self.admin, exclude={User: ['password', 'join_date']})
        self.assertEqual(serialized, {
            'id': self.admin.id,
            'username': '******',
            'active': True,
            'admin': True,
            'email': '',
        })
    
    def test_deserializer(self):
        users = self.create_users()
        
        deserialized, models = self.d.deserialize_object(User(), {
            'id': self.admin.id,
            'username': '******',
            'password': self.admin.password,
            'join_date': self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
            'active': True,
            'admin': True,
        })
        
        for attr in ['id', 'username', 'password', 'active', 'admin']:
            self.assertEqual(
                getattr(deserialized, attr),
                getattr(self.admin, attr),
            )
        
        self.assertEqual(
            deserialized.join_date.strftime('%Y-%m-%d %H:%M:%S'),
            self.admin.join_date.strftime('%Y-%m-%d %H:%M:%S'),
        )
            
        admin_pk = self.admin.id
        
        deserialized, models = self.d.deserialize_object(self.admin, {
            'username': '******',
            'active': False,
            'admin': False,
        })
        
        self.assertEqual(deserialized.username, 'edited')
        self.assertEqual(deserialized.admin, False)
        self.assertEqual(deserialized.active, False)
        self.assertEqual(deserialized.id, admin_pk)
        
        deserialized.save()
        
        self.assertEqual(User.select().count(), 3)
        edited = User.get(username='******')
        self.assertEqual(edited.id, admin_pk)
    
    def test_s_and_d(self):
        self.create_users()
        
        s = self.s.serialize_object(self.admin)
        d, model_list = self.d.deserialize_object(User(), s)
        self.assertEqual(d, self.admin)
Exemple #18
0
 def get_serializer(self):
     return Serializer()
 def setUp(self):
     super(SerializerTestCase, self).setUp()
     self.s = Serializer()
     self.ms = ModelSerializer()
     self.d = Deserializer()
     self.md = ModelDeserializer()
def token():

    error = request.args.get('error', None)
    state = request.args.get('state', None)

    if not (error is None):
        app.logger.info(error)
        app.logger.info(request.args.get('error_description', None))
        prec = processor.updateProcessorRequest(state=state, status=error)

        um.trigger({
            "type": "resource",
            "message": "a resource request has been rejected",
            "user_id": prec.resource.user.id,
            "data": json.dumps(Serializer().serialize_object(prec))
        })

        return "Noted rejection <a href='%s/audit'>return to catalog</a>" % prec.catalog.uri

    code = request.args.get('code', None)

    prec = processor.updateProcessorRequest(state=state,
                                            status="accepted",
                                            code=code)

    if prec is not None:
        url = '%s/client_access?grant_type=authorization_code&redirect_uri=%s&code=%s' % (
            prec.catalog.uri, prec.catalog.redirect_uri, code)
        f = urllib2.urlopen(url)
        data = f.read()
        f.close()
        result = json.loads(data.replace('\r\n', '\n'), strict=False)

        if result["success"]:
            prec = processor.updateProcessorRequest(
                state=state, status="accepted", token=result["access_token"])

            um.trigger({
                "type": "resource",
                "message": "a resource request has been accepted",
                "user_id": prec.resource.user.id,
                "data": json.dumps(Serializer().serialize_object(prec))
            })

            experimenter.perform_execution(prec,
                                           "%d_1" % prec.resource.user.id,
                                           '["%s","%s"]' % (aweekago, now))
            experimenter.perform_execution(prec,
                                           "%d_2" % prec.resource.user.id,
                                           '["%s","%s"]' % (adayago, now))
            experimenter.perform_execution(prec,
                                           "%d_3" % prec.resource.user.id,
                                           '["%s","%s"]' % (anhourago, now))

            return "Successfully obtained token <a href='/experiment'>return to experiment</a>"

#return redirect('/experiment')
        else:
            return "Failed to swap auth code for token <a href='%s/audit'>return to catalog</a>" % prec.catalog.uri

    return "No pending request found for state %s" % state
class SerializerTestCase(FlaskPeeweeTestCase):
    def setUp(self):
        super(SerializerTestCase, self).setUp()
        self.s = Serializer()
        self.d = Deserializer()

    def test_serializer(self):
        users = self.create_users()
        serialized = self.s.serialize_object(self.admin)
        self.assertEqual(
            serialized,
            {
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
                "email": "",
            },
        )

        serialized = self.s.serialize_object(self.admin, fields={User: ["id", "username"]})
        self.assertEqual(serialized, {"id": self.admin.id, "username": "******"})

        serialized = self.s.serialize_object(self.admin, exclude={User: ["password", "join_date"]})
        self.assertEqual(
            serialized, {"id": self.admin.id, "username": "******", "active": True, "admin": True, "email": ""}
        )

    def test_deserializer(self):
        users = self.create_users()

        deserialized, models = self.d.deserialize_object(
            User(),
            {
                "id": self.admin.id,
                "username": "******",
                "password": self.admin.password,
                "join_date": self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S"),
                "active": True,
                "admin": True,
            },
        )

        for attr in ["id", "username", "password", "active", "admin"]:
            self.assertEqual(getattr(deserialized, attr), getattr(self.admin, attr))

        self.assertEqual(
            deserialized.join_date.strftime("%Y-%m-%d %H:%M:%S"), self.admin.join_date.strftime("%Y-%m-%d %H:%M:%S")
        )

        admin_pk = self.admin.id

        deserialized, models = self.d.deserialize_object(
            self.admin, {"username": "******", "active": False, "admin": False}
        )

        self.assertEqual(deserialized.username, "edited")
        self.assertEqual(deserialized.admin, False)
        self.assertEqual(deserialized.active, False)
        self.assertEqual(deserialized.id, admin_pk)

        deserialized.save()

        self.assertEqual(User.select().count(), 3)
        edited = User.get(username="******")
        self.assertEqual(edited.id, admin_pk)

    def test_s_and_d(self):
        self.create_users()

        s = self.s.serialize_object(self.admin)
        d, model_list = self.d.deserialize_object(User(), s)
        self.assertEqual(d, self.admin)