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
Related
I want to access a property exist in the self.context using a variable. I have a variable name "prop" and it contains a value and it is already set in the self.context. I am using Flask Restplus framework.
prop = 'binding'
If I try to access this property like below then it gives me an error:
Object is not subscriptable
I want to know if there is any way to get the value? Like doing this:
print(self.context[prop])
I only get one solution don't know if its correct or not, I tried this :
self.context.__getattribute__(prop)
There are two ways to do this, the simplest is using getattr:
getattr(self.context, prop)
This function internally calls __getattribute__ so it's the same as your code, just a little neater.
However, you still have the problem that you probably only want to access some of the context, while not risking editing values set by different parts of your application. A much better way would be to store a dict in context:
self.context.attributes = {}
self.context.attributes["binding"] = False
print(self.context.attributes[prop])
This way, only certain context variables can be accessed and those that are meant to be dynamic don't mess with any used by your application code directly.
I am working on a machine learning modelling problem where an object is created to store training and validation data, but the validation set if optional and if not included when creating the object the default value is None.
If we find out later on though the user wants to add a validation pandas dataframe we were hoping to let them supply the name of the dataframe with input(). With a function defined right in the notebook we're running we can then do an eval(<input>) to turn the string into the object we need. If we define the object outside of our notebook though it seems like the scope doesn't include that variable.
I realize this probably isn't the best way to do this, so what is a more pythonic way to let a user supply a dataframe by name after an object as already been instantiated? We can pass the objects fine as arguments to functions. Is there a way to pass an object like that but with input() or some other user-friendly way to prompt the user?
It maybe possible to use locals() or globals() as a dict for grabbing an initialized variable by it's name.
the_variable = {'key_one': 'val_one'}
selected_input = input("Please input a variable name")
selected_var = locals()[selected_input]
print("selected_var continence -> {0}".format(selected_var))
Should output, well assuming the_variable was passed to input()
selected_var continence -> {'key_one': 'val_one'}
This is an adaptation of an answer to Calling a function of a module by using it's name a string, but seems to work in this instance too.
Update
I can't remember where I picked up the following perversion (I did look about though), and I'm not suggesting it's use in production. But...
questionable_response = lambda message: input("{message}: ".format(message = message))
this_response = json.loads(questionable_response("Input some JSON please"))
# <- '{"Bill": {"person": true}, "Ted": {"person": "Who is asking?"}}'
... does allow for object like inputting.
And getting data from an inputted json string could look like...
this_response['Bill']
# -> {u'person': True}
this_response['Ted'].get('person')
# -> u'Who is asking?'
... however, you'll likely see some issues with using above with other scripted components.
For the Unicode conversion there's some pre-posted answers on the subject. And checking help(json.loads) exposes that there's toggles for parse_ing floats, ints, and constants.
Even with that it may not be worth it, because there's still some oddities you'll run into if trying to implement this funkiness.
Just to list a few;
conjunctions are a no go; let's say ya get a clever Clara who inputs something like '{"Clara": {"person": "I'll not be labelled!"}}'. That would cause an error unless ' was escaped, eg. \'
the above is also quote fragile; perhaps someone at the keyboard hasn't had enough to drink and tries "{'Jain': {'person': True}}". That would first barf on quotes, then heave from True not being true
So like I prefaced at the start of this update, I'll not recommend this in production; could waist a lot of time chasing edge-cases. I only share it because maybe you've not found any other option for getting from input to something that can be interrogated like an object.
I'm writing the backend of my app in Python and writing to a PyMongo database.
I'm setting up a few servers which I'd like to run simultaneously as nodes in a blockchain. In my prototype, I need each node to create there own collection in my database for their version of the blockchain, so for example blockchain-{insert node_id here} for each.
I'm pretty new to python and have been self teaching myself but struggling to combine .format method with creating these collections.
I know that this works:
client = MongoClient('mongodb://localhost:27017/')
db = client.my_blockchain
col_blockchain = db.name_of_blockchain
Result: Collection named "name_of_blockchain"
But when I try the following, I get an error:
col_blockchain = db['col_my_blockchain_{}'].format(node_id)
Result: Error:
TypeError: 'Collection' object is not callable. If you meant to call the 'format' method on a 'Collection' object it is failing because no such method exists.
Or when I try to save the name in a variable, I don't get a dynamic answer:
col_blockchain_name = 'col_my_blockchain_{}'.format(node_id)
col_blockchain = db.col_blockchain_name
Result: Collection named "col_blockchain_name" for each server running (so not dynamic)
This code:
col_blockchain = db['col_my_blockchain_{}'].format(node_id)
is looking for a dictionary element called col_my_blockchain_{} and when it has retrieved that it's trying to call the string format function on it. What you want to do is:
col_blockchain = db['col_my_blockchain_{}'.format(node_id)]
Which forms the dictionary key fully before trying to access it. All you need to do is move the ]
Use eval keyword, for calling mongo collection
eval('col_my_blockchain.{}'.format(node_id))
this works
Not sure if this is the right place for my question, but I'm dealing with something pretty weird.
In my script, I have a class data() that is just a container for all sorts of constants and sort of data types. One of these data types is a dictionary that looks like this:
testStatus = { 'checkpoint': None,
'tests_Executed': [],
'tests_Passed': [],
'tests_FailedFromRegression': [],
'tests_FailedFromRetest': [],
'tests_PassedFromRetest': [] }
My intention is to use this dictionary as a data type for what I call, last test status and current test status. Somewhere in the constructor of my main class, I have something like this:
self.lastTestStatus = self.testStatus
self.currentTestStatus = self.testStatus
The weird part happens in my run() function of my main class. This is the main worker function of the class. After getting some previously saved status, and building a list with all previously tested items, self.currentTestStatus gets written even if I'm not touching it. The code looks like this:
self.getTestStatus()
#All good after this line.
#This is a function that uses self.lastTestStatus to save the previous status.
#After running this line, self.lastTestStatus["tests_FailedFromRegression"] will hold a list with some items. This is just script testing data.
previouslyTested = []
previouslyTested = self.lastTestStatus["tests_Passed"]
#All good after these two lines.
previouslyTested.extend(self.lastTestStatus["tests_FailedFromRegression"])
#At this point, self.currentTestStatus["tests_Passed"] gets the same value as self.lastTestStatus["tests_FailedFromRegression"] has.
previouslyTested.extend(self.lastTestStatus["tests_FailedFromRetest"])
previouslyTested.extend(self.lastTestStatus["tests_PassedFromRetest"])
Any idea what exactly am I doing wrong here? If I use a testStatus2 for my current status, which is identical with testStatus, everything's fine.
I'm using Python 2.7.10 32bit with Spyder 3.0.0dev.
Thanks a lot!
Just so we have an answer ---
self.lastTestStatus and self.currentTestStatusare references to the same object. When you mutate one, you mutate the other, since they are in fact the same object. Instead do
import copy
self.lastTestStatus = copy.deepcopy(self.testStatus)
self.currentTestStatus = copy.deepcopy(self.testStatus)
in order to copy the dictionaries and the lists they hold -- docs.
I am coding a program that requires access to bitcoin and other cryptocurrency wallets on a remote server. I have it all coded pretty much but one error keeps popping up that causes divide by 0 (wonderful right?)
I am accessing the wallet via this line:
conn = bitcoinrpc.connect_to_remote('####', '###', host=###', port=port)
I assure you the user, pass and ip are all correct. I then proceed to do this
wallet_response = conn.getmininginfo
self._difficulty = wallet_response.difficulty
print 'difficulty'
self._networkhash = wallet_response.networkhashps
print 'network hashrate'
self._blockcount = wallet_response.blocks
print 'blocks'
but it says that "'function' object has no attribute etc"
I have tried to iterate through, accessing attributes by [] but I cannot get it. I thought that .getmininginfo returned an object that i could access the attributes but it returns a function? I have read through the documentation and looked through the code and cannot come up with how to access them.
Anyone seen this before or know how to access the attributes in a function?
I think you are missing parens:
conn.getmininginfo
should be
conn.getmininginfo()