web.py database select access

2020-07-17 16:36发布

问题:

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?

回答1:

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).



回答2:

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.



回答3:

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



标签: python web.py