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.
Related
I'm using Facebook's Python SDK to extract Ads Insights, but I can't find the right way to retrieve ALL fields without having to declare them, which is pretty cumbersome.
My current code looks like this:
ads = tempaccount.get_insights(
params={'date_preset': 'yesterday',
'level': 'ad'},
fields=[AdsInsights.Field.account_id,
AdsInsights.Field.account_name,
AdsInsights.Field.ad_id,
AdsInsights.Field.ad_name,
AdsInsights.Field.adset_id,
AdsInsights.Field.adset_name,
AdsInsights.Field.campaign_id,
AdsInsights.Field.campaign_name,
AdsInsights.Field.cost_per_outbound_click,
AdsInsights.Field.outbound_clicks,
AdsInsights.Field.spend])
Is there a way to force the "fields" attribute to bring all possible fields without declaring them?
Unfortunately, you will need to specify all the required fields. It's not possible to get all fields without explicitly specifying them.
My code also looks similar to yours when querying the insights endpoint.
This worked for me:
from facebookads.adobjects.adsinsights import AdsInsights
for property, value in vars(AdsInsights.Field).items():
print(property, ":", value)
Got from this post: How to enumerate an object's properties in Python?
So I'm trying to learn Python here, and would appreciate any help you guys could give me. I've written a bit of code that asks one of my favorite websites for some information, and the api call returns an answer in a dictionary. In this dictionary is a list. In that list is a dictionary. This seems crazy to me, but hell, I'm a newbie.
I'm trying to assign the answers to variables, but always get various error messages depending on how I write my {},[], or (). Regardless, I can't get it to work. How do I read this return? Thanks in advance.
{
"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true
}
Edited because I put in the wrong sample code.
You need to show your code, but the de-facto way of doing this is by using the requests module, like this:
import requests
url = 'http://www.example.com/api/v1/something'
r = requests.get(url)
data = r.json() # converts the returned json into a Python dictionary
for item in data['answer']:
print(item['widgets'])
Assuming that you are not using the requests library (see Burhan's answer), you would use the json module like so:
data = '{"answer":
[{"widgets":16,
"widgets_available":16,
"widgets_missing":7,
"widget_flatprice":"156",
"widget_averages":15,
"widget_cost":125,
"widget_profit":"31",
"widget":"90.59"}],
"result":true}'
import json
data = json.loads(data)
# Now you can use it as you wish
data['answer'] # and so on...
First I will mention that to access a dictionary value you need to use ["key"] and not {}. see here an Python dictionary syntax.
Here is a step by step walkthrough on how to build and access a similar data structure:
First create the main dictionary:
t1 = {"a":0, "b":1}
you can access each element by:
t1["a"] # it'll return a 0
Now lets add the internal list:
t1["a"] = ["x",7,3.14]
and access it using:
t1["a"][2] # it'll return 3.14
Now creating the internal dictionary:
t1["a"][2] = {'w1':7,'w2':8,'w3':9}
And access:
t1["a"][2]['w3'] # it'll return 9
Hope it helped you.
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
})
I have a json object saved inside test_data and I need to know if the string inside test_data['sign_in_info']['package_type'] contains the string "vacation_package" in it. I assumed that in could help but I'm not sure how to use it properly or if it´s correct to use it. This is an example of the json object:
"checkout_details": {
"file_name" : "pnc04",
"test_directory" : "test_pnc04_package_today3_signedout_noinsurance_cc",
"scope": "wdw",
"number_of_adults": "2",
"number_of_children": "0",
"sign_in_info": {
"should_login": false,
**"package_type": "vacation_package"**
},
package type has "vacation_package" in it, but it's not always this way.
For now I´m only saving the data this way:
package_type = test_data['sign_in_info']['package_type']
Now, is it ok to do something like:
p= "vacation_package"
if(p in package_type):
....
Or do I have to use 're' to cut the string and find it that way?
You answer depends on what exactly you expect to get from test_data['sign_in_info']['package_type']. Will 'vacation_package' always be by itself? Then in is fine. Could it be part of a larger string? Then you need to use re.search. It might be safer just to use re.search (and a good opportunity to practice regular expressions).
No need to use re, assuming you are using the json package. Yes, it's okay to do that, but are you trying to see if there is a "package type" listed, or if the package type contains vacation_package, possibly among other things? If not, this might be closer to what you want, as it checks for exact matches:
import json
data = json.load(open('file.json'))
if data['sign_in_info'].get('package_type') == "vacation_package":
pass # do something
A user needs to pass a json object as a part of the request. It would look something like this:
{"token" :"ayaljltja",
"addresses": [
{'name':'Home','address':'20 Main Street',
'city':'new-york'},
{'name':'work', 'address':'x Street', 'city':'ohio'}
]}
I have two problems right now. First, I can't figure out how to test this code by recreating the nested POST. I can successfully POST a dict but posting the list of addresses within the JSON object is messing me up.
Simply using cURL, how might I do this? How might I do it with urrlib2?
My second issue is then deserializing the JSON POST object on the server side. I guess I just need to see a successful POST to determine the input (and then deserialize it with the json module).
Any tips?
First make sure your JSON is valid. Paste it into the JSONLint web page.
Currently your JSON has two issues:
there is no comma between "token" :"ayaljltja" and "addresses": [...]
a single quote is not a valid way of delimiting a JSON string, replace them all with double quotes.
With command line curl, save your JSON to a file, say data.json. Then try: curl -X POST -d #data.json http://your.service.url
It's also possible to enter the JSON directly to the -d parameter but (as it sounds like you know already) you have to get your quoting and escaping exactly correct.