Converting tuple into list does not work - python

I query my SQlite Database with a loop to retrieve data from it.
connector = sqlite3.connect("somedb.db")
selecter = connector.cursor()
selecter.execute(''' SELECT somedata FROM somedb''')
for row in selecter:
l = list(row)
print (l)
print (type(l))
Then I try do use formatting to append the retrieved data to something else
this = detect.that( "{}", pick, summary).format(l)
But it comes back with this:
AttributeError: 'tuple' object has no attribute 'format'
I also tried this
s = " ".join(str(row) for row in selecter)
for the l = list(row) statement but it comes back with the same errormessage and it seems that it converts all my 50 separate selections into one string what I dont want.
However, when I run this
print (type(l))
or
print (type(s))
it returns me list or stringas a type. So the converting worked, but the .format does not take it because it thinks it is a tuple.
How comes?

Change your detect.that line to this:
this = str(detect.that("{}", pick, summary)).format(1)

Related

TypeError: int() argument must be a string, a bytes-like object or a number, not 'result'

I'm trying to take the highest id and add one to make a new id. When I try to start it (it's at null as nothing is in there yet) it gives me this error: TypeError: int() argument must be a string, a bytes-like object or a number, not 'result'.
#app.route('/new-recipe', methods=['POST'])
def create_recipe(application):
data = request.get_json()
current_id = int(db.session.query(func.max(Recipes.id)).first())
# I've tried without int() too.
if current_id >= 1:
new_id = current_id + 1
new_recipe = Recipes(id=new_id)
return new_recipe.id
else:
new_recipe = Recipes(id=1)
return new_recipe.id
You can use .scalar() to convert from a result to a value.
current_id = db.session.query(func.max(Recipes.id)).scalar()
See https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.scalar
I do, however, have a comment on your approach: it would be better to let the database generate the ids for you, because code like yours could behave unpredictably when multiple people are accessing /new-recipe at the same time.
If you get the last id and then do an insert in a separate query (while not in a database transaction), someone else can insert a record with the same ID, as the one you're attempting to insert, before you. This would cause an error.

Python sqllite3 doesn't return list

I have a list of values (only one value for now)
testList = ["value1"] #or is this an array in python??
and I would like to get this list from database
so I tried like this (assuming I have myTerribleTable in my DB and it has one atribute named "myAtribute" which has values "value1"
conn = sqlite3.connect("mydb.db")
so I execute the query: print(conn.execute(SELECT myAtribute FROM myTerribleTable).fetchall())
so I expect to get back ['value1']
but I get [('value1',)] this is not a list, it looks like a tuple even prepending evething with list like that print(list(conn.execute(SELECT myAtribute FROM myTerribleTable).fetchall())) doesn't work I still get [('value1',)] instead of desired ['value1']
not sure what is happening
Thanks for Anwsering and Best Regards
rows = conn.execute("SELECT myAttribute FROM myTerribleTable").fetchall()
output = List()
for row in rows:
output.append(row.["myAttribute"])
With this loop you could convert the row objects into a list of values
print(list(conn.execute(SELECT myAtribute FROM myTerribleTable).fetchall()[0]))
How about this?

Parse received variables from python flask

How do i parse my received variables into arrays. I receive them from a site and i want to insert them into my firebird database but it would be a lot faster if i could do that through parsing it into a list.
This is how my flask code looks:
#app.route('/fddatumupdate', methods=['GET'])
def fddatumupdate():
datums = request.args.get('datums')
IDS1 = request.args.get('ids1')
IDS2 = request.args.get('ids2')
IDS3 = request.args.get('ids3')
print datums
print IDS1
print IDS2
print IDS3
#cur.execute("UPDATE OR INSERT INTO T_FOOD_DUTY (F_FD_DATE, F_US_ID1, F_US_ID2, F_US_ID3) values(%s, %s, %s) matching (F_FD_DATE)")
return("great succes")
This is the printing output so you can see how my data looks:
2017-5-15,2017-5-16,2017-5-17,2017-5-18,2017-5-19,2017-5-20,2017-5-21
27,36,26,435,26,30,31
27,28,30,435,27,28,26
30,28,30,28,29,28,27
I always get the error when i try to parse them from an NoneType to a string or array:
TypeError: unsupported operand type(s) for +: 'NoneType' and ...
You can split your string by , character and you will get a list:
print datums.split(',')
Alternatively, you can use list comprehensions to construct your list with some extra checking:
# example code
if datums: # this will check if 'datums' is None
print [i if i > 0 for i in datums.split(',')] # include element in list only if it is larger than 0
Found the answer, I parsed my received variables while i was receiving them en putthing them into my local variables. It needs to be like this then:
datums = request.args.get('datums')
IDS1 = request.args.get('ids1')
IDS2 = request.args.get('ids2')
IDS3 = request.args.get('ids3')
datumArray = str(datums).split(',')
IDS1Array = str(IDS1).split(',')
IDS2Array = str(IDS2).split(',')
IDS3Array = str(IDS3).split(',')

How to store list in rows of mysql using Python/Flask?

I am getting some values from a html form and I am storing these values to a list. List is like:
["string1", "string2", "string3", "string4", "string5"]
I want to store these values in rows of mysql but I am confused how to do?
What I did till now is:
descrip = []
descrip.append(description1)
descrip.append(description2)
descrip.append(description3)
descrip.append(description4)
descrip.append(description5)
for r in descrp:
result_descrp = db.execute("""INSERT INTO description(id,description) VALUES (1,%s)""",((descrip))
return render_template('forms/success.html')
But I am getting this error:
TypeError: not all arguments converted during string formatting
At first, You use the placeholder %s in the format string which expect a str. But you pass a list to it.
And I don't know the type of description in your schema. If you just want to save the string presentation of list in the database, you can transform list to str with str(desciption).
And Mysql also support json type of field.(MariaDB also support json type.)
descrip = []
descrip.append(description1)
descrip.append(description2)
descrip.append(description3)
descrip.append(description4)
descrip.append(description5)
for r in range(5):
if descrip[r]:
result_add_event = db.execute("""INSERT INTO event_description(event_id,title,description, created_at) VALUES (%s,%s,%s)""",(id,descrip[r],timestamp))
This above code worked very fine. :)
Special thanks to #shiva and also to those who helped me.

GQL does not work for GET paramters for keys

I am trying to compare the key to filter results in GQL in Python but the direct comparison nor typecasting to int works. Therefore, I am forced to make a work around as mentioned in the uncommented lines below. Any clues?
row = self.request.get("selectedrow")
#mydbobject = DbModel.gql("WHERE key=:1", row).fetch(1)
#mydbobject = DbModel.gql("WHERE key=:1", int(row)).fetch(1)#invalid literal for int() with base 10
#print mydbobject,row
que = db.Query(DbModel)
results = que.fetch(100)
mydbobject = None
for item in results:
if item.key().__str__() in row:
mydbobject = item
EDIT1- one more attempt that does not retrieve the record, the key exists in the Datastore along with the record
mydbobject = DbModel.gql("WHERE key = KEY('%s')"%row).fetch(1)
Am I correct in my assumption that you're basically just want to retrieve an object with a particular key? If so, the get and get_by_id methods may be of help:
mydbobject = DbModel.get_by_id(int(self.request.get("selectedrow")))
The error "invalid literal for int()" indicate that the paramater pass to int was not a string representing an integer. Try to print the value of "row" for debuging, I bet it is an empty string.
The correct way to retrieve an element from the key is simply by using the method "get" or "get_by_id".
In your case:
row = self.request.get("selectedrow")
mydbobject = DbModel.get(row)

Categories