Combining separate self.request.sessions into one request - python

I am trying to optimize and reduce some of my code, and just generally understand it better as this is my first development project.
The below works fine but is it possible to simplify it?
self.request.session['path_one_images'] = PATH_ONE_IMAGES
self.request.session['images'] = images
self.request.session['slider_DV_values'] = slider_DV_values
self.request.session['instruction_task_one_images'] = INSTRUCTION_TASK_ONE_IMAGES
self.request.session['instruction_task_two_images'] = INSTRUCTION_TASK_TWO_IMAGES
I tried to combine the separate requests in one using a dict but get the error:
Exception Value: unhashable type: 'list'
self.request.session({['path_one_images'] : PATH_ONE_IMAGES,
['images'] : images,
['slider_DV_values'] : slider_DV_values,
['instruction_task_one_images'] : INSTRUCTION_TASK_ONE_IMAGES,
['instruction_task_two_images'] : INSTRUCTION_TASK_TWO_IMAGES,})

request.session is a basically a Python mapping just like a dictionary, and it supports all dictionary methods. Like dict.update() to set multiple key-value pairs:
self.request.session.update({
'path_one_images': PATH_ONE_IMAGES,
'images': images,
'slider_DV_values': slider_DV_values,
'instruction_task_one_images': INSTRUCTION_TASK_ONE_IMAGES,
'instruction_task_two_images': INSTRUCTION_TASK_TWO_IMAGES
})
Note that the keys are not lists; you were getting confused by the object[...] subscription syntax there.

you know this is wrong syntax for a dict, yes?
{['path_one_images'] : PATH_ONE_IMAGES}
...should be
{'path_one_images': PATH_ONE_IMAGES, etc}
https://docs.python.org/2/library/stdtypes.html#dict
this explains the error you're getting ("unhashable type: 'list'")... Python thinks you're trying to use a list ['path_one_images'] as the dict key. Dict keys don't have to be strings but they have to be hashable. In this case you just want to use the string 'path_one_images'.
Then additionally, as #Martijn Pieters pointed out, the session dict itself isn't callable, you should use the update method, eg:
self.request.session.update({
'path_one_images': PATH_ONE_IMAGES,
'images': images,
'slider_DV_values': slider_DV_values,
'instruction_task_one_images': INSTRUCTION_TASK_ONE_IMAGES,
'instruction_task_two_images': INSTRUCTION_TASK_TWO_IMAGES
})

Related

Python/Flask add key to inner dictionary

I am trying to construct a dictionary with a list of IDs, which will be used as the response from an API. The dict will be used to generate a JSON response.
I am trying to append a list of IDs that have been affected by the request, but am experiencing an error shown below the code.
I have the following code:
data = {"data" : { "message" : "UPDATED TICKETS SUCCESSFULLY", "status" : 200}}
data['data'].append({"child_ids" : child_sr_ids})
The error that I am getting is: AttributeError: 'dict' object has no attribute 'append'
This seems to contradict other sources that I have read such as this: Appending to list in Python dictionary
I am sure I'm doing something simple wrong but I can't work it out. Would appreciate some direction.
edit: title has been changed to better reflect the correct terminology
data["data"] is not a list. It is a dictionary. There isn't a single list in your code. I think what you want to do here is:
data["data"]["child_ids"] = child_sr_ids
You're not appending to a list, you're adding a key to the inner dictionary. What you're looking for is:
data['data']['child_ids'] = child_sr_ids
simply try the line below or use dict update
data["new key"] = "some new entry"

How to iterate through this nested json array with python

So I made an API call to JIRA to get the list of all the issues. It returns something like this:
{
issues: [
{
fields: {
description:
summary:
creator:
reporter:
priority:
}
}
]
and I'm trying to get to what's inside fields.
Here's what I have:
response = requests.get(url + '/search?jql=resolution%20=%20Unresolved%20order%20by%20priority%20DESC,updated%20DESC', auth=auth).json()
and then :
response['issues'] works. But I can't find a way to access fields and then the elements inside it. I thought about iterating through but not sure if there's a simpler solution.
My understanding is that response[issues] is a list and I know how to access each element of it response[issues][0] but how to access the object nested inside the list? (still researching on it -- might find an answer)
if you look at your json it's an array to a hash or list to dict. To get fields you'd just call the first array element and the key.
response[issues][0][fields]

TypeError: documents must be a non-empty list

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

wildcards in keys of couchdb-python views

The published way to use wildcards in couchdb keys is:
key=somekeyname\ufff0
but that doesn't seem to work in python.
Specifically, my view query is:
results = db.view(docname, key='mykey\ufff0')
I've tried zillions of combinations of ",',\, etc.
I either get no data or the error: TypeError: 'str' object is not callable
I need to find: mykey, mykey=0, mykey=1 mykey_somethingelse, etc.
Any help is appreciated.
"key" parameter doesn't provides wildcard functionality, but direct match with specified value. Probably you'd like to receive all keys that starts with "mykey" value, but only, right? Than you need to use startkey and endkey arguments that defines range of possible view key values to match.
I wounder how and why you get TypeError exception with such description there, but probably you better to describe that problem at couchdb-python issue tracker with full trackeback and used versions. Thanks(:

How can I change urlencode to python dictionary

I have got data from POST like
first_name=jon&nick_name=harry
How can I change this to a python dictionary, like :
{
"first_name":"jon",
"nick_name":"harry"
}
>>> urlparse.parse_qs("first_name=jon&nick_name=harry")
{'nick_name': ['harry'], 'first_name': ['jon']}
If you trust that the URL arguments will always be properly formatted, this would be a minimal solution:
dict(pair.split("=") for pair in urlargs.split("&"))
In code that's going to be publicly accessible though, you'll probably want to use a library that does error checking. If you're using Django, you'll probably have access to them already in the dictionary-like object HttpRequest.POST.

Categories

Resources