Im trying to work with api responses;
Here is the example response that comes from api;
{u'blog': {u'followed': False, u'is_adult': False, u'can_subscribe': False, u'is_nsfw': False, u'ask': True, u'likes': 920, u'is_blocked_from_primary': False, u'can_submit': True, u'ask_anon': True, u'subscribed': False, u'share_likes': True, u'updated': 1493576375, u'description': u'<p>"Che hai dei bellissimi occhi quando mi cerchi."</p><p>18 </p><p>Beginner Wiccan and Witch </p><p>\U0001f312\U0001f315\U0001f318</p>', u'total_posts': 13992, u'submission_page_title': u'Submit', u'submission_terms': {u'title': u'Submit', u'tags': [], u'guidelines': u'', u'accepted_types': [u'text', u'photo', u'quote', u'link', u'video']}, u'name': u'darknessinmyheartt', u'url': u'http://darknessinmyheartt.tumblr.com/', u'ask_page_title': u'lets ask something!/ haydi sor!', u'title': u'"Laurel"', u'posts': 13992, u'reply_conditions': u'3', u'can_send_fan_mail': False}}
how can ı get only the value of u'updated' from that response
u'updated': 1493576375
I have to define that value to "x"
I think the tumblr api response is a python dict, based on that, try:
x = client.blog_info('darknessinmyheartt')
print x['blog']['updated']
You got json response, in Python you can get value from json data, via key.
For your example, you need to do next things:
your_data['blog']['updated']
via your_data['blog'] You will get object with key, values
{'followed': False, u'is_adult': False, u'can_subscribe': False, ....}
and via your_data['blog']['updated'] you will get value 1493576375
Related
I have an array of dictionaries that looks like this :
[{u'description': None, u'url': u'https://epi.testsite.net/index.php?/suites/view/196', u'is_completed': False, u'is_baseline': False, u'completed_on': None, u'is_master': False, u'project_id': 13, u'id': 196, u'name': u'Very Basic'}, {u'description': None, u'url': u'https://epi.testsite.net/index.php?/suites/view/200', u'is_completed': False, u'is_baseline': False, u'completed_on': None, u'is_master': False, u'project_id': 13, u'id': 200, u'name': u'Stress Testing'}]
and some Python code written to extract the 'id' field. Code is as follows :
suites_list = client.send_get ('get_suites/' + pid)
suites_list_ids = [item['id'] for item in suites_list]
return (suites_list_ids)
suites_list generates the data above; suite_list_ids generates a tidy output as follows :
[196, 200]
I would like to pull a second field 'name' and have that included in the output. The desired result like this :
[ {196,'Very Basic'}, {200, 'Stress Testing'} ]
I have been burning many cycles on this one and probably am overlooking something simple. Appreciate any advice.
Dan.
you can do something like this:
suites_list_vals = [(item['id'], item['name']) for item in suites_list]
output:
[(196, 'Very Basic'), (200, 'Stress Testing')]
That is a list of tuples. To iterate on the object you can do something like this:
for val in suites_list_vals:
print(val[0], ':', val[1])
output:
196 : Very Basic
200 : Stress Testing
I have a list of dicts that stores Facebook status data (Graph API):
len(test_statuses)
3
test_statuses
[{u'comments': {u'data': [{u'created_time': u'2016-01-27T10:47:30+0000',
u'from': {u'id': u'1755814687982070', u'name': u'Fadi Cool Panther'},
u'id': u'447173898813933_447182555479734',
u'message': u'Sidra Abrar'}],
u'paging': {u'cursors': {u'after': u'WTI5dGJXVnVkRjlqZFhKemIzSTZORFEzTVRneU5UVTFORGM1TnpNME9qRTBOVE00T1RFMk5UQT0=',
u'before': u'WTI5dGJXVnVkRjlqZFhKemIzSTZORFEzTVRneU5UVTFORGM1TnpNME9qRTBOVE00T1RFMk5UQT0='}},
u'summary': {u'can_comment': False,
u'order': u'ranked',
u'total_count': 1}},
u'created_time': u'2016-01-27T10:16:56+0000',
u'id': u'5842136044_10153381090881045',
u'likes': {u'data': [{u'id': u'729038357232696'},
{u'id': u'547422955417520'},
{u'id': u'422351987958296'},
{u'id': u'536057309903473'},
{u'id': u'206846772999449'},
{u'id': u'1671329739783719'},
{u'id': u'991398107599340'},
{u'id': u'208751836138231'},
{u'id': u'491047841097510'},
{u'id': u'664580270350825'}],
u'paging': {u'cursors': {u'after': u'NjY0NTgwMjcwMzUwODI1',
u'before': u'NzI5MDM4MzU3MjMyNjk2'},
u'next': u'https://graph.facebook.com/v2.5/5842136044_10153381090881045/likes?limit=10&summary=true&access_token=521971961312518|121ca7ef750debf4c51d1388cf25ead4&after=NjY0NTgwMjcwMzUwODI1'},
u'summary': {u'can_like': False, u'has_liked': False, u'total_count': 13}},
u'link': u'https://www.facebook.com/ukbhangrasongs/videos/447173898813933/',
u'message': u'Track : Ik Waar ( Official Music Video )\nSinger : Falak shabir ft DJ Shadow\nMusic by Dj Shadow\nFor more : UK Bhangra Songs',
u'shares': {u'count': 7},
u'type': u'video'},
{u'comments': {u'data': [],
u'summary': {u'can_comment': False,
u'order': u'chronological',
u'total_count': 0}},
u'created_time': u'2016-01-27T06:15:40+0000',
u'id': u'5842136044_10153380831261045',
u'likes': {u'data': [],
u'summary': {u'can_like': False, u'has_liked': False, u'total_count': 0}},
u'message': u'I want to work with you. tracks for flicks',
u'type': u'status'}]
I need to extract each status text and the text of each comment under the status, which I can do by appending them to separate lists e.g.,:
status_text = []
comment_text = []
for s in test_statuses:
try:
status_text.append(s['message'])
for c in s['comments']['data']:
comment_text.append(c['message'])
except:
continue
This gives me two lists of separate lengths len(status_text) = 2, len(comment_text) = 49.
Unfortunately that's a horrible way of dealing with the data since I cannot keep track of what comment belongs to what status. Ideally I would like to store this as a tree structure and export in into a cvs file, but I can't figure out how to do it.
Probable data acv data structure:
Text is_comment
status1 0
status2 0
statusN 0
comment1 status1
comment2 status1
commentN statusN
Why do you need this to be in a CSV? It is already structured and ready to be persisted as JSON.
If you really need the tabular approach offered by CSV, then you have to either denormalize it, or use more than one CSV table with references from one to another (and again, the best approach would be to put the data in an SQL database which takes care of the relationships for you)
That said, the way to denormalize is simply to save the same status text to each row where a comment is - that is: record you CSV row in the innermost loop with your approach:
import csv
status_text = []
comment_text = []
writer = csv.writer(open("mycsv.csv", "wt"))
for s in test_statuses:
test_messages.append(s['message'])
for c in s['comments']['data']:
test_comments.append(c['message'])
writer.writerow((s['message'], c['message']))
Note that you'd probably be better by writing the status idto each row, and create a second table with the status message where the id is the key (and put it in a database instead of various CSV files). And then, again, you are probably better of simply keeping the JSON. If you need search capabilities, use a JSON capable database such as MongoDB or PostgreSQL
The following code stores a unicode dictionary in the variable webproperties_list:
webproperties_list = service.management().webproperties().list(
accountId='~all').execute()
profile_id = webproperties_list.get(u'defaultProfileId')
print profile_id
For some reason the .get() on the key of u'defaultProfileId' is giving me None, even though I know it is in the response. I also tried the get without the u and I still get a None response:
profile_id = webproperties_list.get('defaultProfileId')
Do I need to do something to the dict before I get the value from the key, or am I doing something else wrong entirely?
UPDATE:
Here is the response I get:
{u'username': u'removed', u'kind': u'analytics#webproperties', u'items': [{u'profileCount': 1, u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD', u'defaultProfileId': u'removed'.....
I need to retrieve the value of u'defaultProfileId'
Not really sure how to get a value from a key that is in a dict within a list within a dict...
To figure out how to access it, it sometimes helps to go step by step:
>>> d
{u'username': u'removed', u'items': [{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}], u'kind': u'analytics#webproperties'}
>>> d['items']
[{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}]
>>> d['items'][0]
{u'profileCount': 1, u'defaultProfileId': u'removed', u'kind': u'analytics#webproperty', u'name': u'removed', u'level': u'STANDARD'}
>>> d['items'][0]['defaultProfileId']
u'removed'
I have got Jenkins and python, and some jobs in a queue. I have got a script whic
import jenkins
j = jenkins.Jenkins('http:///', '....', '.......')
queue_info = j.get_queue_info()
print(queue_info)
This command give me the following output:
[{u'task': {u'url': u'http://', u'color': u'aborted', u'name': u'f1111111111'}, u'stuck': False, u'url':
u'queue/item/37/', u'inQueueSince': 1397554800875L, u'actions': [{u'causes': [{u'userName': u'admin', u'userId': u'admin', u'shortDescription':
u'Started by user admin'}]}], u'why': u'Waiting for next available executor on NO_1', u'buildable': True, u'params': u'', u'buildableStartMilliseconds': 1397554800878L, u'id': 37, u'pending': False, u'blocked': False}
How to fetch the name of u'name' and get it to dynamic massive in python
The output is a list of dictionaries, so you can simply access the first entry in the list and use the dictionary's keys.
Let's start by defining a function here:
import subprocess as sp
''' Runs a program '''
def run(prog):
print("Lets run program %s" % prog)
sp.Popen([prog], stdout=sp.STDOUT, stderr=sp.STDOUT)
# This makes the script wait until the end of the program
sp.wait()
Then, in the for loop, you just need to call the run function:
for n in queue_info:
run(n['task']['name'])
I'm use API for upload my backup from server to my google drive. Authorization passed without problems and file is uploaded, but the file does not appear in the list.
Code:
import httplib2
import pprint
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from apiclient.http import MediaFileUpload
f = file('privatekey.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials('1234567890#developer.gserviceaccount.com', key, scope='https://www.googleapis.com/auth/drive')
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
media_body = MediaFileUpload('/path/to/file/document.txt', mimetype='text/plain', resumable=True)
body = {
'title': 'My document',
'description': 'A test document',
'mimeType': 'text/plain'
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)
Response from api:
{u'alternateLink': u'https://docs.google.com/file/d/0B-FWSwzP0SeyamY1MXFIMmFDZWc/edit?usp=drivesdk',
u'appDataContents': False,
u'copyable': True,
u'createdDate': u'2014-01-04T14:41:19.108Z',
u'description': u'A test document',
u'downloadUrl': u'https://doc-0c-6s-docs.googleusercontent.com/docs/securesc/376up7hhina7i2kr3lb8jjr3i1qgs9i8/hbgdu1q3abhdnhdr75jrpjohg4aphvci/1388844000000/08619299632362135867/08619299632362135867/0B-FWSwzP0SeyamY1MXFIMmFDZWc?h=16653014193614665626&e=download&gd=true',
u'editable': True,
u'etag': u'"G9loKy74Mg0FQ-YRqtCj_yTTrpg/MTM4ODg0NjQ3OTAwMw"',
u'fileExtension': u'',
u'fileSize': u'5',
u'iconLink': u'https://ssl.gstatic.com/docs/doclist/images/icon_10_text_list.png',
u'id': u'0B-FWSwzP0SeyamY1MXFIMmFDZWc',
u'kind': u'drive#file',
u'labels': {u'hidden': False,
u'restricted': False,
u'starred': False,
u'trashed': False,
u'viewed': True},
u'lastModifyingUser': {u'displayName': u'1234567890#developer.gserviceaccount.com',
u'isAuthenticatedUser': True,
u'kind': u'drive#user',
u'permissionId': u'08619299632362135867'},
u'lastModifyingUserName': u'1234567890#developer.gserviceaccount.com',
u'lastViewedByMeDate': u'2014-01-04T14:41:19.003Z',
u'md5Checksum': u'ad0234829205b9033196ba818f7a872b',
u'mimeType': u'text/plain',
u'modifiedByMeDate': u'2014-01-04T14:41:19.003Z',
u'modifiedDate': u'2014-01-04T14:41:19.003Z',
u'originalFilename': u'My document',
u'ownerNames': [u'1234567890#developer.gserviceaccount.com'],
u'owners': [{u'displayName': u'1234567890#developer.gserviceaccount.com',
u'isAuthenticatedUser': True,
u'kind': u'drive#user',
u'permissionId': u'08619299632362135867'}],
u'parents': [{u'id': u'0AOFWSwzP0SeyUk9PVA',
u'isRoot': True,
u'kind': u'drive#parentReference',
u'parentLink': u'https://www.googleapis.com/drive/v2/files/0AOFWSwzP0SeyUk9PVA',
u'selfLink': u'https://www.googleapis.com/drive/v2/files/0B-FWSwzP0SeyamY1MXFIMmFDZWc/parents/0AOFWSwzP0SeyUk9PVA'}],
u'quotaBytesUsed': u'5',
u'selfLink': u'https://www.googleapis.com/drive/v2/files/0B-FWSwzP0SeyamY1MXFIMmFDZWc',
u'shared': False,
u'title': u'My document',
u'userPermission': {u'etag': u'"G9loKy74Mg0FQ-YRqtCj_yTTrpg/ebrUqOkKZ6bmVEtr5zEJa5EOB38"',
u'id': u'me',
u'kind': u'drive#permission',
u'role': u'owner',
u'selfLink': u'https://www.googleapis.com/drive/v2/files/0B-FWSwzP0SeyamY1MXFIMmFDZWc/permissions/me',
u'type': u'user'},
u'webContentLink': u'https://docs.google.com/uc?id=0B-FWSwzP0SeyamY1MXFIMmFDZWc&export=download',
u'writersCanShare': True}
Just search for My document in your google drive , you will find this uploaded files
In Drive v3, we could upload using the create function:
A = service.files().create(media_body = 'pig.png',body = {'name':'pig'}).execute()
Although I have tried and this only works for media file types.
API link:
https://developers.google.com/resources/api-libraries/documentation/drive/v3/python/latest/drive_v3.files.html