def test_crud():
    company = Company()
    session.add(company)

    assert [] == crud.object_list(session, company, MyModel)

    obj = crud.create(session, company, MyModel, name='xxx')
    assert obj.name == 'xxx'
    session.commit()

    read_obj = crud.read(session, company, MyModel, obj.id)
    assert read_obj == obj
    assert 1 == crud.object_count(session, company, MyModel)
    assert [read_obj] == crud.object_list(session, company, MyModel)

    crud.update(session, company, MyModel, obj.id, name='aaa')
    session.commit()

    update_obj = crud.read(session, company, MyModel, obj.id)
    assert update_obj.name == 'aaa'

    crud.delete(session, company, MyModel, obj.id)
    delete_obj = crud.read(session, company, MyModel, obj.id)
    assert delete_obj is None

    assert 0 == crud.object_count(session, company, MyModel)
예제 #2
0
def atualizarIngresso(arguments):

    codigo = arguments['codigo']

    nome = arguments['nome']
    qtd = int(arguments['quantidade'])
    horIni = arguments['horarioInicio']
    horTer = arguments['horarioTermino']
    data = arguments['data']
    end = arguments['endereco']
    preco = float(arguments['preco'])

    crud.update(
        {
            "nome": nome,
            "quantidade": qtd,
            "horarioInicio": horIni,
            "horarioTermino": horTer,
            "data": data,
            "endereco": end,
            "preco": preco
        }, "ingresso", "codigo = " + str(codigo))

    ingresso = crud.select("*", "ingresso", "codigo = " + str(codigo))
    return ingresso[0]
예제 #3
0
def venderIngresso(arguments):
    codigo = arguments['codigo']
    quantidade = arguments['quantidade']

    crud.update({"quantidade": quantidade}, "ingresso",
                "codigo = " + str(codigo))

    ingresso = crud.select("*", "ingresso", "codigo = " + str(codigo))
    return ingresso[0]
예제 #4
0
def main():
	while True:
		print(":=="*20)
		print("\t\tCONSOLE CRUD WITH SQLITE3")
		print(":=="*20)
		print("[C]REATE NEW DATABASE")
		print("[D]ROP DATABASE")
		print("[U]SE DATABASE")
		print("[E]xit")
		print(":=="*20)

		try:
			opt = input('Select one option:\n')

			if opt.upper() == 'C':
				crud.clear()
				db.createDB()
			elif opt.upper() == 'D':
				db.dropDB()

			elif opt.upper() == 'U':
				while True:
					print("[1] Insert new record")
					print("[2] Show all records")
					print("[3] Update a record")
					print("[4] Delete a record")
					print("[5] Search a record")
					print("[6] Exit")
					print(":=="*20)
					try:
						option = int(input('Select a option:\n'))

						if option == 1:
							crud.clear()
							crud.create()
						if option == 2:
							crud.clear()
							crud.get()
						if option == 3:
							crud.update()
						elif option  == 4:
							crud.delete()
						elif option == 6:
							crud.clear()
							break
					except:
						print('Option invalid!')	

			elif opt.upper() == 'E':
				break
		except:
			print('Option invalid!')
예제 #5
0
파일: main.py 프로젝트: gsidhu/buzo.dog
async def update(iD: str,
                 title: Optional[str] = None,
                 source: Optional[str] = None,
                 description: Optional[str] = None,
                 tags: Optional[str] = None,
                 language: Optional[str] = None,
                 author: Optional[str] = None,
                 likes: Optional[str] = None):
    queries = {
        '_id': iD,
        'title': title,
        'source': source,
        'description': description,
        'tags': tags,
        'language': language,
        'author': author,
        'likes': likes
    }
    collection = {}
    for k in queries.keys():
        if queries[k] != None:
            if k == 'likes':
                collection[k] = int(queries[k])
            else:
                collection[k] = queries[k]

    response = crud.update(collection)

    if response:
        return {"success": 1}
    else:
        return {"success": 0}
예제 #6
0
def entry():
    req = {}
    if request.method == 'POST':
        req = request.json
        crud.create(req["message"])
        return req
    if request.method == 'GET':
        req = request.json
        retrive = crud.retrive(req["message"])
        return retrive
    if request.method == 'PUT':
        req = request.json
        update = crud.update(req["_id"], req["message"])
        return update
    if request.method == 'DELETE':
        req = request.json
        crud.delete(req["message"])
        return req
    return req
예제 #7
0
def update():
    jsonData = json.loads(request.data)
    crud.update(jsonData)
    response = jsonify(message="Carro atualizado")
    return response
예제 #8
0
    choice = input(
        "Enter the number of the operation you would like to perform: ")

    if choice == "1":
        website_to_create = input(
            "\nEnter the website for which you want the password to be created: "
        )
        password_to_create = input("Enter the password: "******"2":
        website_to_read = input("\nEnter the name of the website: ")
        read(website_to_read)
    elif choice == "3":
        website_to_update = input(
            "\nEnter the website for which you want the password to be updated: "
        )
        password_to_update = input("Enter the new password: "******"4":
        website_to_delete = input(
            "\nEnter the website for which you want the password to be deleted: "
        )
        delete(website_to_delete)
    elif choice == "5":
        print("Goodbye!")
        quit()
else:
    print("Wrong username or password.")
    quit()
예제 #9
0
파일: test.py 프로젝트: kuzovkov/exmobot
import crud
from pprint import pprint

print '-'*80
print 'BEGIN Testing storage.MySQL.crud...'


crud = crud.Crud('store_test')

crud.query('SELECT * FROM session_data')
crud.insert('session_data', [('key1', 'val1', 'str', 'sess1', 1234567890), ('key1', 'val1', 'str', 'sess1', 1234567890), ('key1', 'val1', 'str', 'sess1', 1234567890)])
crud.insert('session_data2', [('key1', 'val1', 'str', 'sess1', 1234567890), ('key1', 'val1', 'str', 'sess1', 1234567890), ('key1', 'val1', 'str', 'sess1', 1234567890)])
pprint(crud.get('session_data', {'session_id2=': "'sess1'", '`key`=': "'key2'"}))
pprint(crud.get('session_data', {'session_id=': "'sess1'", '`key`=': "'key2'"}))
crud.delete('session_data2')
crud.delete('session_data')

crud.insert('session_data', data=[('key2', 'val1', 'str', 'sess1', 1234567890)])


crud.drop_tables()
crud.create_tables()
crud.insert('session_data', data=[('key2', 'val1', 'str', 'sess1', 1234567890)])
crud.update('session_data2', data={'value': 'val3'}, conditions=[{'session_id=': "'sess1'"}, {'utime=':str(1234567890)}])
crud.update('session_data', data={'value': 'val3'}, conditions=[{'session_id=': "'sess1'"}, {'utime=':str(1234567890)}])



print 'END Testing storage.MySQL.crud...'
print '-'*80
예제 #10
0
                secondMenu = True

                inner_decision2 = crud.take_decision()

                while inner_decision2 not in range(1, 8) or None:
                    if inner_decision2 is None:
                        print("{}There is no option like that!{}".format(
                            colors["red_txt_black_bgr"], colors["white_txt"]))
                    inner_decision2 = crud.take_decision()

                if inner_decision2 == 1:
                    crud.create()
                elif inner_decision2 == 2:
                    crud.print_data()
                elif inner_decision2 == 3:
                    crud.update()
                elif inner_decision2 == 4:
                    crud.delete()
                elif inner_decision2 == 5:
                    crud.count_age()
                elif inner_decision2 == 6:
                    crud.count_gender()
                elif inner_decision2 == 7:
                    skipFirst = False
                    secondMenu = False
            else:
                print(
                    "{}There was an error with loading a data file!{}".format(
                        colors["red_txt_black_bgr"], colors["white_txt"]))

        if inner_decision == 2 and not secondMenu:
예제 #11
0
import crud as c

c.create_table()
c.insert('Glass',5,6.5)
c.update(10,45.6,'Lalla')
print(c.view())

예제 #12
0
#INSERINDO dados do BD
#sequencia: id, cpf, nome, nascimento, endereco, cidade, estado
values = [
    "DEFAULT, '12345678911', 'joão pedro', '2019-03-05', 'R teste BD', 'python', 'ND'",
    "DEFAULT, '12345678956', 'karem rodrigues', '2019-03-05', 'R teste BD', 'python', 'ND'"
]
tabela = 'alunos'
crud.insert(values, tabela, cursor, conn)
print(crud.select("*", 'alunos', cursor))

#############################################

#ATUALIZANDO dados do BD

#sequencia: tabela, sets, cursor, conexao, where(se existir)
crud.update("alunos", {
    "nome": "Deidata Naruto",
    "cidade": "Aldeia da Folha"
}, cursor, conn, "id_aluno = 2")
print(crud.select("*", 'alunos', cursor, "id_aluno = 2"))
############################################

#APAGANDO dados do BD
#sequencia: tabela, where, cursor, conexao
crud.delete("alunos", "cidade = 'Conceição do Ouros'", cursor, conn)
print(crud.select(
    "*",
    'alunos',
    cursor,
))
예제 #13
0
    def update(self, request, pk=None):

        try:
            uam_func_sync(request, c.strUAMLink, c.strAppName, c.strAppClient,
                          "File Manager ", "Update",
                          request.session.session_key,
                          request.META.get('HTTP_X_FORWARDED_FOR'))
        except Exception as e:
            logger.info(e)
        user_name = request.user.first_name + request.user.last_name
        try:
            # request = dict(request.data)
            param = {
                'field': 'directory_id',
                'label': 'Directory',
                'user_name': user_name
            }
            # print "\n\n\n@@@@@@data @@",request.data
            # payload = request.data
            # #payload=serializer.data
            # print "original data:%%%%%%%%,",payload
            original_data = crud.get(self.table, c.all,
                                     'where id=' + str(pk))[0]
            # tags = crud.execute("select tag_id from file_manager_directory_tags where directory_id={}".format(pk))
            # shared_ids = crud.execute("select id from file_manager_share where directory_id={}".format(pk))
            # original_data.update({c.tags:list(tags and zip(*tags)[0]),    'shared_ids':list(shared_ids and zip(*shared_ids)[0])})
            # logger.debug("Files:: get_parent_dirs: Parent Files{}".format(original_data))

            # #try:
            # payload.update({"id":pk})
            # tags = payload.pop(c.tags)
            # file_ids=payload.pop("file_ids")
            # parent_id=payload.pop("parent_id")
            # shared_ids = payload.pop("shared_ids")
            # sub_directories=payload.pop("sub_directories")
            # workflow_id=payload.pop(c.workflow_id)
            # response = crud.update(self.table,payload )
            # print "Response",response
            param = {
                'field': 'directory_id',
                'label': 'Directory',
                'user_name': user_name
            }
            original_data = crud.get(self.table, c.all,
                                     'where id=' + str(pk))[0]
            dir_obj = Directory.objects.get(id=pk)
            serializer = DirectorySerializer(dir_obj, data=request.data)
            if serializer.is_valid():

                tag_details = self.tag_change(pk, request.data, "directory")
                new_tag_ids = {}
                old_tag_ids = {}
                added_tag = tag_details.get("added_tag")
                deleted_tag = tag_details.get("deleted_tag")
                new_tag_ids.update(tag_details.get("new_tag_ids"))
                old_tag_ids.update(tag_details.get("old_tag_ids"))
                directory_update = request.data
                for i in directory_update.keys():
                    if i in [
                            c.tags, 'parent_id', 'workflow_id', 'shared_dirs',
                            'file_ids', 'sub_directories'
                    ]:
                        if i == c.tags:
                            update_tag = directory_update.pop(i)
                        else:
                            directory_update.pop(i)
                directory_id = crud.update(self.table, directory_update)
                if added_tag:
                    for tag in added_tag:
                        directory_tag_data = {
                            c.directory_id: directory_id,
                            "tag_id": new_tag_ids.get(tag)
                        }
                        crud.add(c.tag_dir_rel, directory_tag_data)
                if deleted_tag:
                    for tag in deleted_tag:
                        try:
                            crud.execute(
                                "delete from  file_manager_directory_tags where tag_id={} and directory_id={}"
                                .format(old_tag_ids.get(tag), pk), True)
                        except Exception as err:
                            return Response(err)
                logger.debug("Files:: Serializer{}".format(request.data))
                log_view = LogView()
                original_data1 = {}
                map(
                    lambda x: original_data1.update(
                        {str(x): original_data.get(x)}), original_data)
                # original_data1.update({c.tags:old_tag})
                current_data = request.data
                current_data.update({'user_id': request.user.id})
                ChangeTag = {}
                if added_tag:
                    ChangeTag.update({
                        "Added": {
                            c.field: "Tag",
                            "tag": [Tag for Tag in added_tag],
                            "action": "Added"
                        }
                    })
                if deleted_tag:
                    ChangeTag.update({
                        "Removed": {
                            c.field: "Tag",
                            "tag": [Tag for Tag in deleted_tag],
                            "action": "Removed"
                        }
                    })
                log_view.generate_log(
                    current_data,
                    param,
                    original_data1,
                    self.track_fields,
                    ChangeTag,
                )
                return Response(
                    crud.get(self.table, c.all,
                             c.where_id_param.format(directory_id)))
            else:
                logger.debug("Files:: Serializer{}".format(serializer.errors))
                return Response(serializer.errors)
        except Exception as err:
            return Response(err)
예제 #14
0
def update_quote():
    if request.method == 'PUT':
        quote = request.get_json()
    return crud.update(quote)