I trying to create a json object and pass that object to template.render(JSONObj), but there is some error saying
ValueError: dictionary update sequence element #0 has length 1; 2 is required
What am I doing wrong?
You have to give that "JSONObj" object a key value. The template recieves a dictionary with objects and values to render inside it. So, try using this:
template.render(jsonobj=JSONObj)
Then, in your template, you can use this object this way:
{{jsonobj.some_key_inside_json_object}}
This jsonobj is a name that identifies your "JSONObj" object inside the template's arguments.
Hope it helps!
Related
Im currently using the module element tree & urllib to access/parse and return values from xml files.
Using the root.find/root.findall() methods along with XPath syntax to locate desired info in xml. Then using (.text) to return the value of child/grandchild elements.
When assigning each root.find() to a variable then taking the variable and attaching (.text), i am able to parse and return the value with no issues.
(i.e)
x= root.find(./Cameras/Camera/Connected')
print (x.text)
==> True
However I would like to place these "root.find()" in a dictionary and call on them later in the script.
(i.e)
location= {
'Cam': "root.find('./Cameras/Camera/Connected')",
'Mic': "root.findall('./Audio/Input/Connectors/Microphone')",
'Prod_ID': "root.find('./SystemUnit/ProductPlatform')"
}
However, when indexing to dictionary by key and then attempting the add the (.text) i get the following error;
y=location['Cam']
print (y.text)
==> AttributeError: 'str' object has no attribute 'text'
So this maybe a simple issue im overlooking but do these two methods return the same value? Can the element tree module read root.find() from dictionaries?
You're setting your dictionary values to a literal string. That is, this:
'Cam': "root.find('./Cameras/Camera/Connected')",
Is setting the value of key Cam to the string value root.find('./Cameras/Camera/Connected'). You want to actually call the function and set the key to the return value, so you need to drop the quotes:
'Cam': root.find('./Cameras/Camera/Connected'),
I'm trying to pull a list of all the Salesforce Objects (tables names) from Salesforce. In the examples I see of people getting the Object data, the name of the Object is already known. I want to see the entire list of Objects prior to that. Is this possible? I am using simple_salesforce.
Thank you!!!
Nevermind, I found it
for x in sf.describe()["sobjects"]:
print(x["name"])
You can use Schema.getGlobalDescribe().Values() to get descriptions of each object, which are of type Schema.SObjectType. Then you can call the .getDescribe() method to get the object description, then call the .getName() method on the object description to get the object name:
for(Schema.SObjectType objectType : Schema.getGlobalDescribe().Values()){
String name = objectType.getDescribe().getName();
System.debug('Object name is==>' +name);
}
I have this JSON object and i like to update a value within the object. I found a way how i should do this on stackoverflow (Json handling in ROBOT) and its failing and i don't understand why.
This is de object:
{"elementKey":"P690-C0-C3-B1","fields":[{"key":"P690-C1-C2-C1-C1-C1-F0","values":[]},{"key":"P690-C0-C2-F8","values":["1200"]},{"key":"P690-C0-C2-F9","values":["22000"]},{"key":"P690-C0-C2-F11","values":["I"]},{"key":"P690-C0-C2-F10","values":["2200"]},{"key":"P690-C0-C2-C0-C0-F0","values":["98-zsg-2"]},{"key":"P690-C1-C0-C0-F1","values":["Personenauto"]},{"key":"P690-C1-C0-C0-F2","values":["Personenauto KVP"]},{"key":"P690-C0-C2-F6","values":["B"]},{"key":"P690-C0-C2-F7","values":["75"]},{"key":"P690-C0-C2-F4","values":["2"]},{"key":"P690-C0-C2-F5","values":["5"]},{"key":"P690-C0-C2-F2","values":["model"]},{"key":"P690-C0-C2-F3","values":["2017"]},{"key":"P690-C1-C2-C2-C2-C1-F0","values":[]},{"key":"P690-C0-C2-F1","values":["merk"]}]}
In Robot frame I made this test, inspired on the given link.
${json_string}= Set Variable "see text above"
${json}= Evaluate json.loads('''${json_string}''') json
Set To Dictionary ${json["fields"]} ${new_value}
${json_string}= evaluate json.dumps(${json}) json
With ${new_value} i tried value=shizzleliz, value[0]=shizzleliz, value[1]=shizzleliz, P690-C1-C2-C1-C1-C1-F0=shizzleliz
All give the error: AttributeError: 'list' object has no attribute 'update'
When i change ${json["fields"]} to ${json} then the give value is set to the library but not in de fields section/collection.
Does anyone have a clue of what i'm doing wrong? And if you have a suggestion how i can update the value, i'd like that very much :)
target is to change: {"key":"P690-C1-C2-C1-C1-C1-F0","values":[]}
to: {"key":"P690-C1-C2-C1-C1-C1-F0","values":["shizzleliz"]}
For the first part in your question - the error AttributeError: 'list' object has no attribute 'update', you've already seen the comment - you're calling Set To Dictionary on a list object, which cannot pass.
For the second part, in order to set that value when the key is equal to something, you have to iterate over all the list members, and set it based on a condition over the key:
${json_string}= Set Variable see text above
${json1}= Evaluate json.loads('''${json_string}''') json
${target value}= Create List shizzleiz
:FOR ${element} IN #{json1["fields"]}
\ Run Keyword If "${element['key']}" == "P690-C1-C2-C1-C1-C1-F0"
... Set To Dictionary ${element} values=${target value}
${json_string}= evaluate json.dumps(${json1}) json
It looks a little cumbersome in RF (compared to python); one remark - it's never a good idea to name a local variable the same as a module - thus I've renamed it to ${json1}
I found an easier solution using Catenate where I needed to randomize two values in the json body.
${shizzleiz}= shizzleiz # or whatever you want to appear there
${json_string}= Catenate {"elementKey":"P690-C0-C3-B1","fields":[{"key":"P690-C1-C2-C1-C1-C1-F0","values":[]},{"key":"P690-C0-C2-F8","values":["1200"]},{"key":"P690-C0-C2-F9","values":["22000"]},{"key":"P690-C0-C2-F11","values":["I"]},{"key":"P690-C0-C2-F10","values":["2200"]},{"key":"P690-C0-C2-C0-C0-F0","values":["98-zsg-2"]},{"key":"P690-C1-C0-C0-F1","values":["Personenauto"]},{"key":"P690-C1-C0-C0-F2","values":["Personenauto KVP"]},{"key":"P690-C0-C2-F6","values":["B"]},{"key":"P690-C0-C2-F7","values":["75"]},{"key":"P690-C0-C2-F4","values":["2"]},{"key":"P690-C0-C2-F5","values":["5"]},{"key":"P690-C0-C2-F2","values":["model"]},{"key":"P690-C0-C2-F3","values":["2017"]},{"key":"P690-C1-C2-C2-C2-C1-F0","values": ${shizzleiz} ${the-rest-of-the-long-json-as-a-string}
then continue on with:
${json}= Evaluate json.loads('''${json_string}''') json
${json_string}= evaluate json.dumps(${json}) json
(basically do the work before reacting to the json function - obviously this requires knowing the values beforehand and could also work with more variables.)
In a Django view you can access the request.GET['variablename'], so in your view you can do something like this:
myvar = request.GET['myvar']
The actual request.GET['myvar'] object type is:
<class 'django.http.QueryDict'>
Now, if you want to pass multiple variables with the same parameter name, i.e:
http://example.com/blah/?myvar=123&myvar=567
You would like a python list returned for the parameter myvar, then do something like this:
for var in request.GET['myvar']:
print(var)
However, when you try that you only get the last value passed in the url i.e in the example above you will get 567, and the result in the shell will be:
5
6
7
However, when you do a print of request.GET it seems like it has a list i.e:
<QueryDict: {u'myvar': [u'123', u'567']}>
Ok Update:
It's designed to return the last value, my use case is i need a list.
from django docs:
QueryDict.getitem(key)
Returns
the value for the given key. If the
key has more than one value,
getitem() returns the last value. Raises
django.utils.datastructures.MultiValueDictKeyError
if the key does not exist. (This is a
subclass of Python's standard
KeyError, so you can stick to catching
KeyError
QueryDict.getlist(key) Returns the
data with the requested key, as a
Python list. Returns an empty list if
the key doesn't exist. It's guaranteed
to return a list of some sort.
Update:
If anyone knows why django dev's have done this please let me know, seems counter-intuitive to show a list and it does not behave like one. Not very pythonic!
You want the getlist() function of the GET object:
request.GET.getlist('myvar')
Another solution is creating a copy of the request object... Normally, you can not iterate through a request.GET or request.POST object, but you can do such operations on the copy:
res_set = request.GET.copy()
for item in res_set['myvar']:
item
...
When creating a query string from a QueryDict object that contains multiple values for the same parameter (such as a set of checkboxes) use the urlencode() method:
For example, I needed to obtain the incoming query request, remove a parameter and return the updated query string to the resulting page.
# Obtain a mutable copy of the original string
original_query = request.GET.copy()
# remove an undesired parameter
if 'page' in original_query:
del original_query['page']
Now if the original query has multiple values for the same parameter like this:
{...'track_id': ['1', '2'],...} you will lose the first element in the query string when using code like:
new_query = urllib.parse.urlencode(original_query)
results in...
...&track_id=2&...
However, one can use the urlencode method of the QueryDict class in order to properly include multiple values:
new_query = original_query.urlencode()
which produces...
...&track_id=1&track_id=2&...
I'm doing a program using Twitter API and MongoDB in 2.7 Python language.
I get a timeline and put it in a dictionary, which I want to store in a MongoDB database. To do this I have next code:
def saveOnBD(self, dic):
client = MongoClient("xxxx", "port")
db = client.DB_Tweets_User_Date
collection = db.tweets
collection.insert_many(dic)
I'm debbuging and dic it's not empty but I get next error:
TypeError: documents must be a non-empty list
How can I fix it?
I trying many options, but i solved that question changing the post method.
Instead of:
collection.insert_many(dic)
I used this:
collection.insert_one(dic)
I supose that, as I try to post only a variable(dic) and "insert_many()" is for many variables that retun me the error. That change solved me the question
you can either put in an entry before running the bulk entry function or use insert()
A list of documents must be passed to insert_many method
E.g.:
collection.insert_many([dic])