How to use dynamic variable in python mongodb script - python

I want to update records in the collection books.
I want to create new field whose name and value are the values from variables.
for book in db.books.find():
title = book['title']
author, value = getAuthor(title)
db.dataset.update({"_id": book['_id']}, {"$set": {author: value}})
When I did this I got the error: WriteError: The update path contains an empty field name. It is not allowed which is not true because both variables have values. I googled and resolved this issue by enclosing author into []. So the code looks like this:
for book in db.books.find():
title = book['title']
author, value = getAuthor(title)
db.dataset.update({"_id": book['_id']}, {"$set": {[author]: value}})
But now I am getting this error which I am not able to resolve:
TypeError: unhashable type: 'list'
Does anyone have encountered such problem? How can I resolve it?

It sounds like getAuthor() is returning back nothing for it's first value, so author is getting set to nothing. From what I can see you did not resolve the error, you just changed it to a different error. By making it say [author] (though it's been a while since I've been in Python) I believe you're just trying to set the key to be an empty list, or a list with an empty string as the only value, depending on what author is.
If I were you, I would print out what author is, or do some debugging and figure out what you're getting back from getAuthor(). Since I can't see that code, nor the data in your database, I'm not sure how to help further without more information.

Related

AttributeError:'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'DESCRIPTOR'

def get_ad_full_details(ad_json, current_topics, ad_group_ad, ad):
mandatory_data = {
"ad_group_ad.ad.responsive_search_ad.headlines": ad_group_ad.ad.responsive_search_ad.headlines,
"ad_group_ad.ad.responsive_search_ad.descriptions": ad_group_ad.ad.responsive_search_ad.descriptions}
ad_json["mandatory_data"] = mandatory_data
when I run json.dumps(ad_json) I get AttributeError:'google.protobuf.pyext._message.RepeatedCompositeCo' object has no attribute 'DESCRIPTOR'. I've tried to follow this post but it still gives the same error.
I've tried to iterate and map the ad_group_ad.ad.responsive_search_ad.headlines repeated protof field to its "[text]" values, but the code fails.
Any idea, how I can fetch the "text" member of this repeated proto field?
I can use regex, but thought their might be an easier way

SmartSheet API python extended object

There are several objects in the SmartSheet SDK API which are extensions of objects. For instance, CellLink and ObjectValue are an extensions of the Cell object. I've done some reading and understand that these are parent/child classes and involve inheritance. However, this concept still escapes me and I cannot figure out the syntax for creating a CellLink object.
new_cell = ss.models.Cell()
linked_cell = ss.models.Cell()
linked_cell.column_id = int(columnid)
linked_cell.sheet_id = int(sheetid)
linked_cell.row_id = int(rowid)
new_cell.link_in_from_cell = linked_cell
The example above gives me the most informative error message therefore, I assume it is the closest to the correct syntax of all the variations I have tried. Any help with this example and possibly the underlying concept would be greatly appreciated.
raise ValueError("`{0}` invalid type for {1} value".format(value,
self.object_type))
ValueError: `{"columnId": 2068210422966148}` invalid type for <class
'smartsheet.models.cell_link.CellLink'> value
I believe I have found the answer to this question. It seems as though you just need to create a dictionary of the attributes like:
ex_dict = {sheet_id: 0974792938, column_id: 07263839242, row_id:
2632938474839}
new_cell.link_in_from_cell = ex_dict
The trick is later in the code. Instead of creating a new row like:
row = ss.models.Row()
You need to update an existing row like:
row = ss.Sheets.get_row(sheet_id, row_id)
However, I am still having a weird error of:
Field \"createdAt\" was of unexpected type.
You should be sending Row and Cell objects with only the properties that you wish to change. You do not want to attempt to modify an existing Row object (e.g. with the createdAt property, but rather allocate a new one with appropriate row id and cells to update.
See https://github.com/smartsheet-samples/python-snippets/blob/04951c2ca8ae1a97386bdd3fa6e010f2845e1421/samples.py#L45 for a complete example of creating a cell link.

Python- how to query database by class

I have a Python project (I'm quite new to Python), and on one of the webpages, there is a drop-down box which should display a list of all of the projects whose 'status' fields are set to 'live'.
It seems that a couple of particular objects are not being displayed in this drop-down box, so I want to manually query the database to check what their 'status' fields are set to.
How do I manually query the database for these particular projects by their 'project name'/ 'project code', both of which I know are unique?
I've tried getting a list of all of the projects in the shell, so that I can query that list by project_name for the particular projects that I want using the commands:
from projects.models import Project
prjcts = []
prjcts = Project.objects.all()
This gets all of the Project objects and assigns them to the list prjcts. I now want to query that list for a particular project, and have tried doing so like this:
6Stoke = prjcts.get(project_code = 6SPR)
My intention was that the project with the project_code whose value was 6SPR would be assigned to the variable 6Stoke, so that I could then find look at all of the information for that particular project. However, when I tried running this line in the console, I got a
SyntaxError: invalid syntax
warning which highlighted the end of the 6Stoke part of the line.
What is wrong with my syntax here? How can I get the project that has the specified project_code and assign it to a variable?
Edit
Ah, ok- thanks. I changed the variable name, and ran the query again, assigning its results to the variable sixStokeList, i.e.
sixStokeList = Project.objects.filter(project_code = "6SPR")
this returned two items, and having printed the elements of the array to the console, i.e. sixStokeList[0] & sixStokeList[1], I know which one I want, so I've assigned that particular one to a variable with:
sixStoke = sixStokeList[1]
I have then typed sixStoke. and pressed 'tab' in the console to see what's available to this variable. I did the same with another project, i.e.
theFoss = Project.objects.filter(project_code= "1TF")
theFoss. (& pressed 'tab')
The list of available options given after typing variable + . + tab was different for each project instance, even though I had got them both in exactly the same way, which would indicate to me that they are not instances of the same class... how can this be, given that I got them both by querying the same class?
You can't name a variable beginning with a number

SalesforceObject.search/get not working together? Python / Simple-salesforce

Heres what I'm trying to do:
First of all, I want every entry in Account. After that, I want to use get on them to get the whole thing. However, I get an error message. I do the following:
accIdArr = sf.search("FIND {Account}")
print accIdArr
for i in accIdArr:
print i["Id"]
accDataArr = sf.Account.get(i["Id"])
print accDataArr
However, I get this error message:
simple_salesforce.api.SalesforceResourceNotFound: Resource Account Not Found. Response content: [{u'errorCode': u'NOT_FOUND', u'message': u'The requested resource does not exist'}]
I then tried to use sf.Account.get('CopyAndPastedId') with the Id that got printed before I get the error, eg i["Id"].
Well, that doesnt work either and gives the same error. So I thought about Account not existing, however sf.Account.metadata() works fine and gives the expected data.
What am I doing wrong?
Is there a reason to use SOSL rather than SOQL?
Since you are only requesting the Account Objects, a simple SOQL search will get you what you want. Try the following:
accDataDict = sf.query('SELECT ID, Name, <all other fields you want> FROM Account')
The return will be an ordered dictionary of all the Account Objects with the field/values you requested in your query.

Using Strings to Name Hash Keys?

I'm working through a book called "Head First Programming," and there's a particular part where I'm confused as to why they're doing this.
There doesn't appear to be any reasoning for it, nor any explanation anywhere in the text.
The issue in question is in using multiple-assignment to assign split data from a string into a hash (which doesn't make sense as to why they're using a hash, if you ask me, but that's a separate issue). Here's the example code:
line = "101;Johnny 'wave-boy' Jones;USA;8.32;Fish;21"
s = {}
(s['id'], s['name'], s['country'], s['average'], s['board'], s['age']) = line.split(";")
I understand that this will take the string line and split it up into each named part, but I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes.
The purpose of the individual parts is to be searched based on an individual element and then printed on screen. For example, being able to search by ID number and then return the entire thing.
The language in question is Python, if that makes any difference. This is rather confusing for me, since I'm trying to learn this stuff on my own.
My personal best guess is that it doesn't make any difference and that it was personal preference on part of the authors, but it bewilders me that they would suddenly change form like that without it having any meaning, and further bothers me that they don't explain it.
EDIT: So I tried printing the id key both with and without single quotes around the name, and it worked perfectly fine, either way. Therefore, I'd have to assume it's a matter of personal preference, but I still would like some info from someone who actually knows what they're doing as to whether it actually makes a difference, in the long run.
EDIT 2: Apparently, it doesn't make any sense as to how my Python interpreter is actually working with what I've given it, so I made a screen capture of it working https://www.youtube.com/watch?v=52GQJEeSwUA
I don't understand why what I think are keys are being named by using a string, when just a few pages prior, they were named like any other variable, without single quotes
The answer is right there. If there's no quote, mydict[s], then s is a variable, and you look up the key in the dict based on what the value of s is.
If it's a string, then you look up literally that key.
So, in your example s[name] won't work as that would try to access the variable name, which is probably not set.
EDIT: So I tried printing the id key both with and without single
quotes around the name, and it worked perfectly fine, either way.
That's just pure luck... There's a built-in function called id:
>>> id
<built-in function id>
Try another name, and you'll see that it won't work.
Actually, as it turns out, for dictionaries (Python's term for hashes) there is a semantic difference between having the quotes there and not.
For example:
s = {}
s['test'] = 1
s['othertest'] = 2
defines a dictionary called s with two keys, 'test' and 'othertest.' However, if I tried to do this instead:
s = {}
s[test] = 1
I'd get a NameError exception, because this would be looking for an undefined variable called test whose value would be used as the key.
If, then, I were to type this into the Python interpreter:
>>> s = {}
>>> s['test'] = 1
>>> s['othertest'] = 2
>>> test = 'othertest'
>>> print s[test]
2
>>> print s['test']
1
you'll see that using test as a key with no quotes uses the value of that variable to look up the associated entry in the dictionary s.
Edit: Now, the REALLY interesting question is why using s[id] gave you what you expected. The keyword "id" is actually a built-in function in Python that gives you a unique id for an object passed as its argument. What in the world the Python interpreter is doing with the expression s[id] is a total mystery to me.
Edit 2: Watching the OP's Youtube video, it's clear that he's staying consistent when assigning and reading the hash about using id or 'id', so there's no issue with the function id as a hash key somehow magically lining up with 'id' as a hash key. That had me kind of worried for a while.

Categories