Ejemplo n.º 1
0
 def test_set_data(self):
     data = Data('name')
     expected = Template(data=[data])
     template = Template()
     template.data = [data]
     self.assertIsInstance(template.data, Array)
     self.assertEqual(template, expected)
Ejemplo n.º 2
0
 def test_set_template_dict(self):
     template = Template(data=[Data("name")])
     expected = Collection('href', template=template)
     collection = Collection('href')
     collection.template = template.to_dict()["template"]
     self.assertIsInstance(collection.template, Template)
     self.assertEqual(collection, expected)
Ejemplo n.º 3
0
 def test_template_minimal_to_dict(self):
     template = Template()
     expected = {
         'template': {
             'data': [],
         }
     }
     self.assertEqual(template.to_dict(), expected)
Ejemplo n.º 4
0
 def test_template_to_dict(self):
     data = [Data('name')]
     template = Template(data)
     expected = {
         'template': {
             'data': [
                 {'name': 'name'}
             ]
         }
     }
     self.assertEqual(template.to_dict(), expected)
Ejemplo n.º 5
0
 def test_template_from_json_collection(self):
     expected = {
         'collection': {
             'template': {
                 'data': [
                     {'name': 'name', 'value': 'value'},
                     {'name': 'name1', 'value': 'value1'},
                 ]
             }
         }
     }
     data = json.dumps(expected)
     with self.assertRaises(ValueError):
         Template.from_json(data)
Ejemplo n.º 6
0
 def test_template_from_json_no_error(self):
     expected = {
         'template': {
             'data': [
                 {'name': 'name', 'value': 'value'},
                 {'name': 'name1', 'value': 'value1'},
             ]
         }
     }
     data = json.dumps(expected)
     template = Template.from_json(data)
     self.assertEqual(template.to_dict(), expected)
Ejemplo n.º 7
0
def table_post(table:str):
	if request.method == 'POST':
		data = Template.from_json(request.form['payload'])
		mods = data.to_dict()['template']['data']
		names = []
		values = []
		for x in mods:
			values.append(x['value'])
			names.append(x['name'])
		_SQL = """insert into """ + table + """ ("""
		for row in names:
			if  str(row[0]) != "id":
				_SQL += """""" + str(row) + ""","""
		_SQL = _SQL[:-1]
		_SQL += """) values ("""
		for row2 in names:
			_SQL +=  """%s,"""
		_SQL = _SQL[:-1]
		_SQL += ")"
		with DBcm.UseDatabase(DBconfig) as cursor:
			cursor.execute(_SQL,(values))
		_SQL3 = "SELECT id FROM "+table+" ORDER BY id DESC LIMIT 1"
		with DBcm.UseDatabase(DBconfig) as cursor:
			cursor.execute(_SQL3,)
			data5 = cursor.fetchall()
			temp = ','.join(str(v) for v in data5[0])
		test = ""
		test += """{"collection":{"version" : "1.0","href": "http://localhost:5000/table/post/"""+table+"""","""
		test += """ "links": [
			  { "href" : "http://localhost:5000/table/showall/""" + table+""""},
			  { "href" : "http://localhost:5000/table/showone/"""+table+"""/"""+temp+""""}]}}"""
		return str(test)
	else:
		with DBcm.UseDatabase(DBconfig) as cursor:
			_SQL = "SHOW columns FROM " + table  #this is used to get the columns name and value.
			cursor.execute(_SQL,)
			data2 = cursor.fetchall()
		test = ""
		test += """{"collection":{"version": "1.0","href": "http://localhost:5000/table/showall/"""+table+"""","""
		test +=   """  "template": {"data" : [ """
		for row2 in data2:
			if  str([0]) != "id":
				test += """ { "name" : " """ + str(row2[0]) + """" , "value":" """+str(row2[1])+"""" },""" 
		test = test[:-1]
		test += """]}}}"""
		return str(test)
Ejemplo n.º 8
0
 def create(self, model, data, **kwargs):
     """
     Create a new instance of a model
     :param model: The model name to create an instance of
     :type model: str
     :param data: The data to provide to that instance, formatted as a Collection+JSON data array
     :type data: list
     :return: Collection representation of the created resource.
     """
     try:
         data = Template(data)
     except (TypeError, ValueError, IndexError):
         abort(400)
     # letting this raise a KeyError on purpose, flask returns HTTP 500 on python errors
     instance = self.models[model](data)
     session = sessionmaker(bind=self.database)
     session.add(instance)
     session.commit()
     return Collection(href=self.app.config.get('API_ROOT'),
                       items=[instance.get_collection_item()])
Ejemplo n.º 9
0
    def update(self, model, data, pk=None, **kwargs):
        """
        Update a model instance in the database.
        :param model: The model name to look for an instance of.
        :param data: The data to provide to the instance, formatted as a Collection+JSON data array
        :param pk: The primary key of the model instance to modify.
        :param kwargs:
        :return: A Collection+JSON representation of the updated model instance.
        """
        try:
            data = Template(data)
        except (TypeError, ValueError, IndexError):
            abort(400)

        # letting self.models[model] raise a KeyError on purpose, see above
        instance = self.models[model].query.get_or_404(pk)
        instance.update(data)
        self.database.session.commit()
        return Collection(
            href=self.app.config.get('API_ROOT'),
            template=self.models[model].get_collection_template(),
            items=[instance.get_collection_item()])
Ejemplo n.º 10
0
 def test_set_data_invalid(self):
     template = Template()
     invalid_obj = object()
     with self.assertRaises(TypeError):
         template.data = invalid_obj
def post_table():
    if request.method == 'POST':                    # If a template has been received
        template_data = request.get_json(force=True)
        template_to_str = json.dumps(template_data)

        template = Template.from_json(template_to_str)
        table_name = template.table.value

        if table_name == "games":
            name = template.name.value
            description = template.description.value
            with DBcm.UseDatabase(app.config["DB_CONFIG"]) as cursor:
                _SQL = "INSERT INTO games (name, description) VALUES (%s, %s)"
                cursor.execute(_SQL, (name, description,))
                row_id = cursor.lastrowid       # return the id of the row inserted

        elif table_name == "players":
                handle = template.handle.value
                first = template.first.value
                last = template.last.value
                email = template.email.value
                password = template.password.value

                with DBcm.UseDatabase(app.config["DB_CONFIG"]) as cursor:
                    _SQL = "INSERT INTO players (handle, first, last, email, passwd) VALUES (%s, %s, %s, %s, %s)"
                    cursor.execute(_SQL, (handle, first, last, email, password,))
                    row_id = cursor.lastrowid

        elif table_name == "scores":
            game_id = template.game_id.value
            player_id = template.player_id.value
            score = template.score.value

            with DBcm.UseDatabase(app.config["DB_CONFIG"]) as cursor:
                _SQL = "INSERT INTO scores (game_id, player_id, score) VALUES (%s, %s, %s)"
                cursor.execute(_SQL, (game_id, player_id,  score,))
                row_id = cursor.lastrowid

        collection.links = [Link(href='/api/table/showall?name=' + str(table_name), rel='GET'),
                            Link(href='/api/table/showone?name=' + str(table_name)+'&row=' + str(row_id),
                                 rel='GET')]

        return Response(json.dumps(collection.to_dict(), indent=4, sort_keys=True),
                        status=201, mimetype='application/vnd.collection+json')

    elif request.method == 'GET':                   # else send back a Template for the requested table
        parser = reqparse.RequestParser()
        parser.add_argument('name', help='Name of the Table')
        args = parser.parse_args()
        table_name = args['name']

        if table_name is None:                      # if no argument found, return 400, "Bad Request"
            return Response(status=400, mimetype='application/vnd.collection+json')

        else:
            if table_name == "games":
                collection.template = Template(data=[Data(name='table', value='games'),
                                                     Data(name='name', value=''),
                                                     Data(name='description', value='')])
            elif table_name == "players":
                collection.template = Template(data=[Data(name='table', value='players'),
                                                     Data(name='handle', value=''),
                                                     Data(name='first', value=''),
                                                     Data(name='last', value=''),
                                                     Data(name='email', value=''),
                                                     Data(name='password', value='')])
            elif table_name == "scores":
                collection.template = Template(data=[Data(name='table', value='scores'),
                                                     Data(name='game_id', value=''),
                                                     Data(name='player_id', value=''),
                                                     Data(name='score', value='')])
        return Response(json.dumps(collection.to_dict(), indent=4, sort_keys=True),
                        status=200, mimetype='application/vnd.collection+json')
    else:
        return 'Unsupported HTTP method: {}.'.format(request.method)