Extract information from a tuple and place in different variables

Asked

Viewed 360 times

0

I’m beginner and I’m caught in a problem I don’t even know how to research right.

This is what happens: My code needs to select data from a database table (so far so good), and then need to separate the data into other variables as I will mount a json to send the information to dynamoDB.

I need to know how to extract the information from my variable that received all data from my table.

And if possible, how do I send my json all lines of the same.

If anyone has at least some material for me to read and have a north, it would be very helpful. Thank you!

#######################################################
####ETAPA - BUSCANDO INFORMAÇÕES NO FIREBIRD########
#######################################################
print('ETAPA - BUSCANDO INFORMAÇÕES NO FIREBIRD')


##Executar select
try:

    sql = "SELECT * FROM USUARIO"
    cursor.execute(sql);
    USUARIO = cursor.fetchall()

except Exception as e:
    print('')
finally:
    print(USUARIO)

    somedict = {"USU_ID": [x[0] for x in USUARIO],
                "USU_NOME": [x[0] for x in USUARIO],
                "USU_USUARIO": [x[0] for x in USUARIO]
                }

print(somedict)

#######################################################
####SEPARANDO INFORMAÇÕES PARA CRIAR ARQUIVO JSON########
#######################################################

USU_ID = somedict[USU_ID]
USU_NOME = somedict[USU_NOME]
USU_USUARIO = somedict[USU_USUARIO]


###################################################
##ETAPA - CHAMANDO API PARA POST##################
###################################################
#print('MONTANDO ARQUIVO JSON PARA POST')

payload = {
    "USU_ID":USU_ID,
    "USU_NOME":USU_NOME,
    "USU_USUARIO":USU_USUARIO

}

print(str(payload))
try:
    ENVINDO POST PARA API
    url = 'https://l.execute-api.us-east-2.amazonaws.com/dev/gravar'
    print('URL API Post: ', url)
    headers = {
          "Content-Type": "application/json",
          'Accept': 'application/json'
      }
    response = requests.post(url, json=payload, headers=headers)

except Exception as e:
   print('ERRO ac chamar API para o POST')

finally:
      print('O POST foi bem sucedido')
      print(response.text)

Essa é a tabela que estou copiando para dentro da variavel USUARIOS

Esse é o retorno do print da variavel usuarios

  • Can show what USUARIO returns you? So it’s easier to test your code. Another thing: why do you use exceptions just to print something on the screen? And more: why use Exception as e if you don’t use the e?

  • Which JSON you need to send?

  • @Murilositonio I am reusing a code, so it has the 'Exception as' without the 'e'. I print on the screen to understand what is happening in the code rs.

  • @Andersoncarloswoss then, was reading and it seems that to transform my variable into a json array (n know if this makes sense), would need to transform this tuple into a list.. JSON model is one I learned and tested to impute in dynamoby. I don’t know if I answered correctly what you questioned...

  • @Andersoncarloswoss maybe this will help you understand, https://stackoverflow.com/questions/50000536/convert-list-of-objects-to-json-array, the guy who posted this, in the middle of the question has the json matrix model that I would need, because it should be a json for each row of my table.

2 answers

0

I think first of all, you should take a step back and study about how manipulate lists (you are always assigning the same list to all fields in somedict) and as a JSON is structured (First you store an array (although always the same) and then not). Since you have not specified how you want your JSON to be structured I will put two ways below:

Storing each column in an array:

payload = {
            "USU_ID": [x[0] for x in USUARIO],
            "USU_NOME": [x[1] for x in USUARIO],
            "USU_USUARIO": [x[2] for x in USUARIO]
            }

Separating the information by user

payload_all = {"user_1": {
                "USU_ID": USUARIO[0][0],
                "USU_NOME": USUARIO[0][1],
                "USU_USUARIO": USUARIO[0][2]
                },
            "user_2": {
                "USU_ID": USUARIO[1][0],
                "USU_NOME": USUARIO[1][1],
                "USU_USUARIO": USUARIO[2][2]
                },
            "user_3": {
                "USU_ID": USUARIO[2][0],
                "USU_NOME": USUARIO[2][1],
                "USU_USUARIO": USUARIO[2][2]
                },
            "user_4": {
                "USU_ID": USUARIO[3][0],
                "USU_NOME": USUARIO[3][1],
                "USU_USUARIO": USUARIO[3][2]
                },
            "user_5": {
                "USU_ID": USUARIO[4][0],
                "USU_NOME": USUARIO[4][1],
                "USU_USUARIO": USUARIO[4][2]
                }
            } 
  • Hi Murilo. Thank you very much for the answer. I will study yes (I am already doing this). I will base myself on your answer to have a north. Basically I need to popular my table in DYNAMOBY, or it is briefly necessary to take the table of Firebird and impute in DYNAMODB, not yet entered in my head how do I make it work, whenever run the script, it go in the table and get all the lines to mount the JSON.

  • What problem did you get with the above payloads?

  • Then, in my scenario, I would have to automate, for him to assemble this payload_all. The way he removes all the rows from the tables. This will be a script in the future, we imagine that the table will always have update, my code will have to go through the first row of the table until the last one. Yeah, I’ll have an identical table at DYNAMOBD that will receive that information. In addition, I need him to assemble the JSON matrix in order to send it to dynamodb. I’m going to take a deep look at that, I don’t know if I was clear on my goal.

  • Because you at all times Do you have to go through all the lines? Just go through the existing lines to Dynamo and update it when your database has any new entries. What is a "JSON matrix"? The variable payload is a structure in JSON format.

  • I have an inventory database (product count). Today the software records the information in Firebird, with each new count the bank is zeroed. So the script, it will 'clone' the tables because I will use the information in another location and I will pull from dynamoDB. this table users is a simple table of the system I took to develop the logic, but the complex table is itself of the counts of the products, which can vary up to 40 thousand lines. So I’m trying to come up with a logic that takes the information from my table, assemble the json with all the lines. mt thing :\

  • Now I understand better. Consider including as much information as possible to make a good question. Every time I use a Nosql bank I go for Mongo, then I may not be able to help much more. Anyway, Dynamo is also document-oriented, right? So you intend to include all those 40k lines in a single document? (Since you indicated the structure payload_all...)

  • Murilo, correct me if I am talking nonsense but as a json is formed by key and value, I would have to have a result similar to [{'USU_ID': 1}, {'USU_NOME': "TEST"}, {'USU_USUARIO': "ADMINISTRATOR"}, that for each row of my table.

  • I’m sorry, I really couldn’t be objective. But that’s right, I need to include all the lines in a single JSON document for the post

Show 3 more comments

0


[Edit 2] From what I see, Python is returning a list[], within this list, it has several tuples(), and within tuples it has values. Good you can do so.

# Vou considerar que o seu retorno é este:
lista = [(1,'ADMINISTRADOR','ADMIN','CIENTISTA'),(2,'CEO','USER','PROGRAMADOR'),(3,'ALEATÓRIO','USER','BIÓLOGO')]

# Retorna a primeira tupla dentro da lista -> (1, 'ADMINISTRADOR', 'ADMIN', 'CIENTISTA')
print(lista[0])

# Retorna o terceiro item da tupla 2 -> 'USER'
print(lista[1][2])

You can use loops to fetch values, say you want to see all the positions, like:

  • ADMINISTRATOR
  • CEO
  • RANDOM

You can create a loop like this:

# Ande por todas as tuplas da lista retornada
for x in lista:
    # Mostre todos os valores nas posições 1
    print(x[1])

The return will be this:

  • ADMINISTRATOR
  • CEO
  • RANDOM

So you can already have a sense of how to play with this data. I went straight to the point, I hope I helped. I recommend one studied in lists, tuples and dictionaries in python3.

  • 1

    Gabriel, your answer was important for me to create a north here and study the possibilities. I will apply in my code and check if I can solve. Thank you for your time!

  • 1

    @Rodolfosousa His editing made in this reply was not appropriate. If you have another question, even if it is related, then please ask another question (or edit the current question if it is still related to the same problem). You can even link to this answer (if you ask another question), if it helps give more context to your question. But do not add new questions to existing answers.

  • 1

    @Gabriel, your answer was very useful because I was able to understand the logic of lists and tuples, this time I go to the second level that would automate this code. I put a second question on the site: https://answall.com/questions/397041/automatizar-get-de-umartist-de-tuplas-para-vari%C3%a1veis-json .

  • Perfect, the basic difference is that lists are mutable, you can change the values of good, the doubles are permanent, Gustavo Guanabara can give you a great help in this. https://youtu.be/N1hTsbW50eM

Browser other questions tagged

You are not signed in. Login or sign up in order to post.