I am a beginner in python where is the error - python

#python
sql="UPDATE bebliothequee SET title=:titl,author=:autho,ISBN=:ISB WHERE oid='{}'.format(oid.get())",title='{}'.format(title_editor.get()),author='{}'.format(author_editor.get()),ISBN='{}'.format(ISBN_editor.get()),oid='{}'.format(record_id.get())

Your first mistake is that you didn't read Stackoverflow documentation how to create good question. So you didn't add all details in question - and we can't read in your mind - and we can't help it.
Next mistake: you put code in comment but you should put it in question so it would be more readalbe but what is more important: all people could see it and help you.
Code shows that you try to create sql =... with all arguments for execute() and later use it in execute() but it doesn't work this way. You can't assing positional and named values to variable and later put it in function. You should use it directly in execute() or you should create list/tuple with positional variables and dictionary with named variables.
BTW: you don't need '{}'.format() to convert it to strings. You could use str() but I think execute() should convert it automatically.
query = "UPDATE bebliothequee SET title=:title, author=:author, ISBN=:ISBN WHERE oid=:oid"
execute(query, title=title_editor.get(), author=author_editor.get(), ISBN=ISBN_editor.get(), oid=record_id.get())
Other problem is that you use :titl but you should use full name :title like in argument title=....
You have also oid='{}'.format(oid.get() inside query which is totally useless.
BTW: Eventually you can create dictionary
args = {
'title': title_editor.get(),
'author', author_editor.get(),
'ISBN': ISBN_editor.get(),
'oid': record_id.get(),
}
and then you can use ** to unpack it as named arguments
execute(query, **args)

Related

Using kwargs with filter_by (Sqlalchemy)

So I'm currently trying to create a dynamic function, that will take 1 kwarg, and use that in it's filter_by.
This is what the function currently looks like:
def Get_from_var(session, **data):
for entry in data:
if bool(session.query(Tutor).filter_by(entry=data[entry]).first()):
return session.query(Tutor).filter_by(entry=data[entry]).first()
return "No tutor found"
I know that my function will only recieve 1 kwarg, so I'm not worried about some weird exceptions. But currently it seems that the 'entry' paramter in both of the filter_by functions, are interpreted literally, and not as variables? Because It tells me that "tutor has no property 'entry'"
This is how I'm currently calling it:
tutor = Tutor.Get_from_var(session, tutor_id=filters["id"])
You can use **data in filter_by directly to get the correct result.
session.query(Tutor).filter_by(**data).first()
** unpacks your data into key-value pairs and passes them to the filter_by function.
Also, you probably dont want to query twice just to check your if statement.

Use dictionary to resolve argument in Python

I am new to python and learning Dictionary. I am ended up writing the following program in which I am trying to use dictionary to resolve the argument.
Program :
def fun1(self)
options = {'abc': '123', 'edf': '456'}
args = {'op': options[self.arg]}
Now, let's assume that I am passing either 'abc' or 'edf' as argument which I am successfully storing in arg.
Now, what I want to do here is that I want to fetch value according to the key that passed as argument and want to store that value in op
So, is there any problem here in my approach? Are the dictionary tend to use this way? How to achieve this with or without Dictionary?
I use mapping dictionaries like this extensively, they are a good way to avoid mutliple if/elif/else statements.
Just be sure to catch missing keys:
args = {'op': options.get(self.arg, None)}
Or if you don't want to store anything in args:
args = {'op': options[self.arg]} if self.arg in options else None

pyes 'from' keyword can't be set

Since from is a special python keyword I am not able to pass it pyes.es.search function. It give syntax error. pyes.es.search(maf, "twitter", "tweet", sort="timestamp", size=2, from=3) . I passed keyword arguments containing from also as below but from did not work while other worked.
keywords = {'sort': 'timestamp', 'size':3, 'from':2}
r = pyes.es.search(maf, "twitter", "reply",**keywords)
This problem also available for another python elasticsearch module here here. In search function interface there is from argument.
Did you try with start parameter?
It sounds like the one to use.
See http://pyes.readthedocs.org/en/latest/references/pyes.queryset.html#pyes.queryset.QuerySet.start

Benefit of initializing dictionary in function call

I was looking at this code on the Google Map API website:
import simplejson, urllib
GEOCODE_BASE_URL = 'http://maps.googleapis.com/maps/api/geocode/json'
def geocode(address,sensor, **geo_args):
geo_args.update({
'address': address,
'sensor': sensor
})
url = GEOCODE_BASE_URL + '?' + urllib.urlencode(geo_args)
result = simplejson.load(urllib.urlopen(url))
print simplejson.dumps([s['formatted_address'] for s in result['results']], indent=2)
if __name__ == '__main__':
geocode(address="San+Francisco",sensor="false")
I noticed that in the geocode function, when we actually apply the function we don't use the geo_args dictionary when we call the function, but we instead use it to initialize a dictionary we update in the next lines. What is the benefit of using this, as opposed to initializing the dictionary within the function itself? It makes the code a bit less clear so I assume there is a reason for doing it.
geo_args is used. The literal dictionary
{
'address': address,
'sensor': sensor
}
updates geo_args, not the other way around.
The reason it's like this looks to me that address and sensor are required arguments. This structure allows the function to enforce that requireness, and also allow them to be passed positionally. The .update() is just there to consolidate all the arguments into one so they can be given to urllib.urlencode.
Not clear? This is the normal behaviour of **kwargs (the keyword argument dictionary).
So when you see something with **, a bunch of named parameters or keyword arguments will be passed.
Seeing the other answers. I probably misunderstood your question. I agree with the other answers: address and sensor are required.

web.py database select access

I have been messing around with web.py lately and wanted to grab some stuff from a db and its returning me a "Storage" object. an the code i am using to call my info is:
db = web.database(dbn='sqlite', db='sqlfile.sqlite')
sely = db.select('carp', order="id ASC")
when sely runs it drops me out text like so:
<Storage {'lvl': 0, 'symbol': u'formb', 'logged': u'false', 'id': 1, 'display': u'Classic'}>
when you print out sely the storage line comes out. how can i get the dictionary out of this object?
A general Python trick for dealing with unknown APIs is to use the dir builtin. Try dir(sely) in the interpreter to see what member variables and functions are defined for the object you get.
If you see something like __iter__, you can call list(sely) to convert the results to a list, and generally iterate over the object in a loop.
If you see something like __getitem__, then you can index into the object and hope to get a value back.
As a side note, I just tried out your code and I get sely to be a web.utils.IterBetter instance (which returns 0 rows, instead of expected 3 in my case). So I cannot really reproduce your problem (but have problems of my own, so to speak).
db = web.database(dbn='sqlite', db='sqlfile.sqlite')
sely = db.select('carp', order="id ASC").list()
sely would be a list of storages, storage is the same as dict, but you can access arguments with obj.key, instead of obj["key"]. You can do dict(obj) to convert storage into dict.
in windows
return list(db.select('top',what='score',where="name = $id",vars=locals())
is ok. you can get the scoreā€˜s value.
but
in ubuntu
you shuld do it like this
db.select('top',what='score',where="name = $id",vars=locals())[0]["score"]
i don't know why but it works in my computer

Categories

Resources