Based on the MongoKit documentation, I define a nested sturcture use dictionary. But when saving the object, I got an error. Details are as below. Can you please kindly advise?
Thanks
class Swap(Document):
structure = {
'coupon': float
'start': int,
'end': int,
'bdc': {
'start': basestring,
'payment': basestring
}
}
And the error I got are:
bson.errors.InvalidDocument: Cannot encode object: {'start': 'M', 'payment': 'M'}
Just to follow up on this. This error only happens when I turn on "use_dot_notation = True". I noticed there was a post w.r.t the same issue back in Jun 2013, and also has no response. So I will turn this flag off for now.
Related
I am using an existing dictionary:
my_dict = {a: [(1,2,3), (4,5,6)]}
*example
and I have defying a func that gets a new keys and values to my_dict:
def adding_new():
my_dict[new_key] = [(7,8,9)]
i need the dict to update and be saved in my program, but it keeps staying the same as started.
any suggestions?
edit:
Actually I get why you answer that, im pretty sure im not asking my question right.. im new at python and english isnt my spoken language
What im asking is why when i call my function, I dont see any changes in my code? I mean, is there any way to make my program to make changes in my existing code?
It's a bit difficult to tell from your code..
But I think your main problem is that you are just defining a function and not calling the function.
First I fixed the syntax of your code:
my_dict = {"a": (1,2,3), "b": (4,5,6)}
def adding_new():
my_dict["new_key"] = (7,8,9)
Secondly I add a call of the fuction you defined:
my_dict = {"a": (1,2,3), "b": (4,5,6)}
def adding_new():
my_dict["new_key"] = (7,8,9)
adding_new()
When I run this code:
from luno_python.client import Client
import json
c = Client(api_key_id='<api_id>', api_key_secret='<api_secret>')
try:
bal = c.get_balances(assets='NGN')
print(bal)
except Exception as e:
print(e)
I get this output:
{'balance': [{'account_id': 'xxxxxxxxxxxxxxxx', 'asset': 'NGN', 'balance': '0.000274', 'reserved': '0.00', 'unconfirmed': '0.00'}]}
>>>
What I need is anytime I run:
>>>print(bal)
Let me get only this portion as output:
0.000274
{'balance': [{'account_id': 'xxxxxxxxxxxxxxxx', 'asset': 'NGN', 'balance': '0.000274', 'reserved': '0.00', 'unconfirmed': '0.00'}]}
I need only the highlighted portion above
Any help will be appreciated. Thanks in advance.
I don't know if what you get is a dict, but seems like it. Anyways, you just need to get the values by its keys as following:
bal['balance'][0]['balance']
or much safer to avoid using another try and exception :
bal.get('balance',[{'balance':'when bal is empty'}])[0].get('balance')
I am validating json request data for my service. There are many fields, each with their own validators. My plan is to turn the request into a frozen dataclass, if all validations are successful. A validation can fail for reasons that require additional data to explain the cause. If the request is invalid, I want to report this data back to the client so that the user knows why the request was unsuccessful.
Example: The request has a field with an array of fruit.
request = {
'fruit': [{'type':'apple', 'price':5}, {'type': 'banana', 'price': 7}]
}
To validate the fruit field I use a function validate_fruit(fruit: list) which checks the types and values. If there is a fruit with price > 5 I say the request is invalid. I send a response with an error return code and want to specify which fruit is too expensive.
Example: Here, return code 12 means "there are fruit that are too expensive". Error data should give details.
response = {
'return_code': 12
'error_data': ['banana']
}
I would like to use exceptions to implement this. So validate_fruit can raise an Exception with a dict that specifies the return code and additional error data.
I am thinking about
def validate_fruit(fruit: list):
failures = [elem['type'] for elem in fruit if elem['price'] > 5]
if failures:
raise ValueError(data={'error_data': failures, 'return_code': 12})
try:
validate_fruit(fruit)
except Exception as error:
if error.return_code == 12:
...
Has anyone had the same idea? How do you do this?
you can use something like:
try:
raise ValueError({'error_data': ['banana'], 'return_code': 12})
except Exception as ex:
if ex.args[0]["return_code"] == 12:
print("error 12")
I am creating a class and setting some properties. And I am referencing dictionary as a class object. But not able to access the second element of the object.
I tried to google the problem but it does not specify the cause of my problem.
data = {
'a': {
'vsdf': 'asfas',
'nfgn': 'aser',
'aser': 'rtydf'
},
'b': ['ndfg', 'ndf', 'safd']
}
My class looks something like this:
def __init__(self, meta):
self.meta = meta
and when i create the object of this class like this:
request = Request(data)
and try to print the request['b'] it shows the error "'Request' object is not subscriptable"
Actual result should be like :
['', '', '']
but it shows:
'Request' object is not subscriptable
With the code you have given, the data dictionary will be stored in the meta instance variable. You'll need to access it by first accessing that variable, i.e. request.meta['b'].
In order to get it to act the way you want, you'll need to loop through the dict passed in to __init__ and set each variable individually. Take a look at this answer for how to do that: Set attributes from dictionary in python
I have a web service written in Python 3.4 that uses the Falcon framework. One particular method accepts a post of json values. My code:
try:
raw_json = req.stream.read()
except Exception as ex:
raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message)
try:
result_json = json.loads(raw_json.decode('utf-8'))
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400,
'Malformed JSON', 'Could not decode the request body. The JSON was incorrect.')
clientIp = result_json['c']
wpIp = result_json['w']
lan = result_json['l']
table = int(result_json['t'])
This code was working fine 9 months ago but currently throws the error: "list indices must be integers or slices, not str." I think it likely broke after a Python or Falcon package update.
The ouput of raw_json.decode('utf-8') looks ok, returning [{"w": "10.191.0.2", "c": "10.191.0.3", "l": "255.255.255.0", "t": "4"}]. I think json.loads() is the root of my problem. len(result_json) is returning 1 where I would expect 4. Is there an additional parameter needed for json.loads() to help it parse correctly? Or am I missing something else entirely?
Thanks,
Greg (Python noob)
The returned result [{"w": "10.191.0.2", "c": "10.191.0.3", "l": "255.255.255.0", "t": "4"}] is a json array, which is parsed into a python list. Therefore
result_json['c']
produces the the mentioned error. Maybe there was a change in the API and it now returns an array where it previously returned a json object.
This should work:
clientIp = result_json[0]['c']
...