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)
Related
I'm trying to implement a hash table/hash map in Python.
Say I'm using tuples as keys like this:
hashTable = {}
node = [1, 2, 3]
print(hashTable[tuple(node)]) # throws an error
hashTable[tuple(node)] = True
print(hashTable[tuple(node)]) # prints TRUE
I want to check if elements exist in the hashTable before adding it. I have tried initializing the dictionary with all False values.
hashTable = {}
for i in range(1000):
hashTable[i] = False
So this creates a hash table of size 1000 with every slot set to FALSE. But if I try to check if a non-existent element is in the hashTable:
print(hashTable[tuple(node)])
I get the same error as before.
How does one go about doing this? I think this would work iterating through the dict with in but doesn't that defeat the whole purpose of using a hash table in the first place?
Accessing a key is similar to, but not necessarily the same as checking if it exists. To check if a key is in a dictionary, use dict.__contains__ via the in operator. To check if it is missing, use the not in operator:
key = tuple(node)
if key not in hashTable:
hashTable[key] = value
That being said, a totally valid way to check for containment can be by attempting access:
key = tuple(node)
try:
# attempt to use hashTable[key]
except KeyError:
# Do something with missing key
The advantage of doing it this way when both paths are needed is that you only need to access the dictionary once rather than twice.
Try to avoid calling tuple(node) over and over: it's not free. If you can, generate node as a tuple, do so. If not, perform the conversion once and use the converted value.
You can use the in operator to determine membership in a dictionary:
e.g.
if tuple(node) in hashTable:
x = hashTable[tuple(node)]
...
You can try to get the key and in case it is not in de dictionary yet, return a default value as may be None:
x = hashTable.get(node, default=None)
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.
I have a variable output which can take the values #1,#2 ,
i am trying to get the value in "reasons" IF IT EXISTS,as you can see from #1 it does not exist always, can anyone suggest how this can be done?
output =
#1: {"took":42,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":null,"hits":[]}}
#2: {"took":88,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
OUTPUT:-
12345 is associated with data in an invalid state
Well, start with the logic:
hits inside hits may always be there... In additions hits looks to be a list, so you can test if hits (inside hits) is present and if it's not empty (you could test its length, for example).
Once you know that hits is there, you have to go inside that object and check if the value you're looking for is there.
When you have a dictionary in Python, you can retrieve values using the following syntax:
new_value = some_dictionary.get('some_key', None)
That value "None" at the end is the value Python gives me back if there is no value associated with that key. You can put whatever value you want in there and then check for it later on:
new_value = some_dictionary.get('some_key', 'BETTER ASK STACKOVERFLOW')
You have to just try stuff. Use the REPL.
Also, the following is not anything I've ever seen in Python. What gave you this error message:
12345 is associated with data in an invalid state
Ignore KeyErrors where necessary. There are possibly multiple reasons, so the following code gathers them all to a list, then join together using ', ' as the separator.
value = { "took":88,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
reasons = []
for i in value['hits']['hits']:
try:
reasons.extend(i['_source']['reasons'])
except KeyError:
pass
reason = ', '.join(reasons)
This should do it:
adict = {"took":42,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":0,"max_score":"null","hits":[]}}
bdict = {"took":88,"timed_out":False,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":1,"max_score":1.0,"hits":[{"_index":"dispatcher","_type":"lookaheadDV","_id":"832238","_score":1.0, "_source" : {"reasons": ["12345 is associated with data in an invalid state"]}}]}}
def get_reasons(some_dict):
output = ""
try:
output = some_dict.get("hits").get("hits")[0].get("_source").get("reasons")
except:
pass
return output
print get_reasons(adict)
print get_reasons(bdict)
prints nothing for the first dictionary and prints
12345 is associated with data in an invalid state
for the second dictionary.
PS: I changed false to False and null to "null" in your dictionaries.
I've been programming for less than four weeks and have run into a problem that I cannot figure out. I'm trying to append a string value to an existing key with an existing string stored in it but if any value already exists in the key I get "str object has no attribute 'append'.
I've tried turning the value to list but this also does not work. I need to use the .append() attribute because update simply replaces the value in clientKey instead of appending to whatever value is already stored. After doing some more research, I understand now that I need to somehow split the value stored in clientKey.
Any help would be greatly appreciated.
data = {}
while True:
clientKey = input().upper()
refDate = strftime("%Y%m%d%H%M%S", gmtime())
refDate = refDate[2 : ]
ref = clientKey + refDate
if clientKey not in data:
data[clientKey] = ref
elif ref in data[clientKey]:
print("That invoice already exists")
else:
data[clientKey].append(ref)
break
You can't .append() to a string because a string is not mutable. If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list. The easiest way to do this is just to add the single item as a list in the first place.
if clientKey not in data:
data[clientKey] = [ref] # single-item list
Now you can data[clientkey].append() all day long.
A simpler approach for this problem is to use collections.defaultdict. This automatically creates the item when it's not there, making your code much simpler.
from collections import defaultdict
data = defaultdict(list)
# ... same as before up to your if
if clientkey in data and ref in data[clientkey]:
print("That invoice already exists")
else:
data[clientKey].append(ref)
You started with a string value, and you cannot call .append() on a string. Start with a list value instead:
if clientKey not in data:
data[clientKey] = [ref]
Now data[clientKey] references a list object with one string in it. List objects do have an append() method.
If you want to keep appending to the string you can use data[clientKey]+= ref
When running the following code I would like to be able to store the returned values in a variable as a string. However when I run the code it will return the first name from the database in this format
[(u'Kiefer',)]
What would I need to change in order to just return a clean string? I was thinking I could use strip although I have never used it on a tuple (not even sure if you can) but I was hoping there is a more elegant way. Also I am using the sqlite3 module.
def search_db(self,ID,FName,LName):
#try:
FName +='%'
LName += '%'
self.cur.execute(("""SELECT FirstName FROM members WHERE FirstName LIKE '%s'\
AND LastName LIKE '%s'""") % (FName, LName))
value = (self.cur.fetchall())
print(value)
#except:
#print('failed')
cla = Database()
cla.search_db(1,'K','D')
You need to access the first element of the list, which is the tuple, then the first element of the tuple, so:
value[0][0]