Python - iterate through a list - python

I'm trying to automate email reporting using python. My problem is that i cant pull the subject from the data that my email client outputs.
Abbreviated dataset:
[(messageObject){
id = "0bd503eb00000000000000000000000d0f67"
name = "11.26.17 AM [TXT-CAT]{Shoppers:2}"
status = "active"
messageFolderId = "0bd503ef0000000000000000000000007296"
content[] =
(messageContentObject){
type = "html"
subject = "Early Cyber Monday – 60% Off Sitewide "
}
}
]
I can pull the other fields like this:
messageId = []
messageName = []
subject = []
for info in messages:
messageId.append(str(info['id']))
messageName.append(str(info['name']))
subject.append(str(info[content['subject']]))
data = pd.DataFrame({
'id': messageId,
'name': messageName,
'subject': subject
})
data.head()
I've been trying to iterate though content[] using a for loop, but i can't get it to work. Let me know if you have any suggestions.

#FamousJameous gave the correct answer:
That format is called SOAP. My guess for the syntax would be info['content']['subject'] or maybe info['content'][0]['subject']
info['content'][0]['subject'] worked with my data.

Related

Cannot access custom column values in To-do tasks via MS Graph API using Python

I have created custom columns "VESSEL NAME", "VOYAGE NUMBER", "ETD" and "CUT-OFF" in my Outlook To-do task as shown on the pic below.
Outlook tasks snapshot
I need to access values in those columns via MS Graph API, but have had no luck so far.
Not sure if I am moving in the right direction, but I have added an openTypeExtension named "ZZZ" to my task as a test. I can retrieve it via the 'GET' method, but cannot locate it anywhere in Outlook hoping to find it amongst custom columns or other task fields.
Here is the Python code:
# In[1]:
import json
import requests
# In[2]:
token = json.load(open('ms_graph_state.jsonc'))["access_token"]
header = {'Authorization':'Bearer '+token}
header1 = {'Authorization':'Bearer '+token,'Content-Type':'application/json'}
base_url = 'https://graph.microsoft.com/v1.0/me/'
# In[3]:
task_list_id = requests.get(base_url+'todo/lists/',headers=header).json()['value'][1]['id']
task_list = base_url+'todo/lists/'+task_list_id
task_id = requests.get(task_list+'/tasks/',headers=header).json()['value'][0]['id']
# In[4]:
payload = {"#odata.type" : "microsoft.graph.openTypeExtension","extensionName" : "ZZZ","xxx" : "yyy"}
# In[5]:
create_oe = requests.post(task_list+'/tasks/'+task_id+'/extensions',headers=header1,json=payload).json()
# In[6]:
oe = requests.get(task_list+'/tasks/'+task_id+'/extensions/ZZZ',headers=header1).json()
oe
'''
Output:
{'#odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('to-do-app%40outlook.co.nz')/todo/lists('AQMkADAwATZiZmYAZC0xNDM3LTZlYmMtMDACLTAwCgAuAAADtVcV-o2b90KtdxZu_nQLmgEA2HIj8QQFbES8Q4ESBpmcmgAAAgESAAAA')/tasks('AQMkADAwATZiZmYAZC0xNDM3LTZlYmMtMDACLTAwCgBGAAADtVcV-o2b90KtdxZu_nQLmgcA2HIj8QQFbES8Q4ESBpmcmgAAAgESAAAA2HIj8QQFbES8Q4ESBpmcmgAAAUeYHQAAAA%3D%3D')/extensions/$entity",
'extensionName': 'ZZZ',
'id': 'microsoft.graph.openTypeExtension.ZZZ',
'xxx': 'yyy'}
'''
# In[7]:
task = requests.get(task_list+'/tasks/'+task_id,headers=header).json()
task
'''
Output:
{'#odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('to-do-app%40outlook.co.nz')/todo/lists('AQMkADAwATZiZmYAZC0xNDM3LTZlYmMtMDACLTAwCgAuAAADtVcV-o2b90KtdxZu_nQLmgEA2HIj8QQFbES8Q4ESBpmcmgAAAgESAAAA')/tasks/$entity",
'#odata.etag': 'W/"2HIj8QQFbES8Q4ESBpmcmgAAAa4dUQ=="',
'importance': 'normal',
'isReminderOn': False,
'status': 'notStarted',
'title': 'test-to-do-task',
'createdDateTime': '2021-08-14T20:14:22.5557165Z',
'lastModifiedDateTime': '2021-08-17T06:46:46.260686Z',
'id': 'AQMkADAwATZiZmYAZC0xNDM3LTZlYmMtMDACLTAwCgBGAAADtVcV-o2b90KtdxZu_nQLmgcA2HIj8QQFbES8Q4ESBpmcmgAAAgESAAAA2HIj8QQFbES8Q4ESBpmcmgAAAUeYHQAAAA==',
'body': {'content': '\r\n\r\n', 'contentType': 'text'}}
'''
Appreciate you help on this.
Thank you
AFAIK, this is currently not supported. Being said that, consider filing user voice for your specific scenario so it could be considered for future implementation.

Running multiple querys on YouTube API by looping through title columns of CSV python

I am using YouTubes API to get comment data from a list of music videos. The way I have it working right now is by manually typing in my query and then writing the data to a csv file and repeating for each song like such.
query = "song title"
query_results = service.search().list(
part = 'snippet',
q = query,
order = 'relevance', # You can consider using viewCount
maxResults = 20,
type = 'video', # Channels might appear in search results
relevanceLanguage = 'en',
safeSearch = 'moderate',
).execute()
What I would like to do is use the title and artist columns from a csv file that I have containing the song titles I am trying to gather data for so I can run the program once without having to manually type in the song each time.
A friend suggested using something like this
import pandas as pd
data = pd.read_csv("metadata.csv")
def songtitle():
for i in data.index:
title = data.loc[i,'title']
title = '\"' + title + '\"'
artist = data.loc[i,'artist']
return(artist, title)
But I am not sure how I would make this work because when I run this, it is only returning the final row of data, and even if it did run correctly, how I would handle getting the entire program to repeat it self for every instance of a new song.
you can save song title and artist to a list, the loop over that list to get details.
def get_songTitles():
data = pd.read_csv("metadata.csv")
return data['artist'].tolist(),data['title'].tolist()
artist, song_titles = get_songTitles()
for song in song_titles:
query_results = service.search().list(
part = 'snippet',
q = song,
order = 'relevance', # You can consider using viewCount
maxResults = 20,
type = 'video', # Channels might appear in search results
relevanceLanguage = 'en',
safeSearch = 'moderate',
).execute()

Python microsoft graph api

I am using microsoft graph api to pull my emails in python and return them as a json object. There is a limitation that it only returns 12 emails. The code is:
def get_calendar_events(token):
graph_client = OAuth2Session(token=token)
# Configure query parameters to
# modify the results
query_params = {
#'$select': 'subject,organizer,start,end,location',
#'$orderby': 'createdDateTime DESC'
'$select': 'sender, subject',
'$skip': 0,
'$count': 'true'
}
# Send GET to /me/events
events = graph_client.get('{0}/me/messages'.format(graph_url), params=query_params)
events = events.json()
# Return the JSON result
return events
The response I get are twelve emails with subject and sender, and total count of my email.
Now I want iterate over emails changing the skip in query_params to get the next 12. Any method of how to iterate it using loops or recursion.
I'm thinking something along the lines of this:
def get_calendar_events(token):
graph_client = OAuth2Session(token=token)
# Configure query parameters to
# modify the results
json_list = []
ct = 0
while True:
query_params = {
#'$select': 'subject,organizer,start,end,location',
#'$orderby': 'createdDateTime DESC'
'$select': 'sender, subject',
'$skip': ct,
'$count': 'true'
}
# Send GET to /me/events
events = graph_client.get('{0}/me/messages'.format(graph_url), params=query_params)
events = events.json()
json_list.append(events)
ct += 12
# Return the JSON result
return json_list
May require some tweaking but essentially you're adding 12 to the offset each time as long as it doesn't return an error. Then it appends the json to a list and returns that.
If you know how many emails you have, you could also batch it that way.

GAE post does not show directly after put

I have a very simple "guestbook" script on GAE/Python. It often happens however, that entries which I put() into the datastore are not showing right away - I almost always need to refresh.
def post(self):
t = NewsBase(
date = datetime.now(),
text = self.request.get('text'),
title = self.request.get('title'),
link = self.request.get('link'),
upvotes = [],
downvotes = [],
)
t.put()
q = db.GqlQuery('SELECT * FROM NewsBase ORDER BY date DESC')
template_values = {
'q' : q,
'user' : user,
'search' : search
}
template = jinja_environment.get_template('finaggnews.html')
self.response.out.write(template.render(template_values))
I'm sure there is a solution to this?
Best,
Oliver
This is due to the eventual consistency model of HRD.
You should really read some of the intro docs, Structuring Data for Strong Consistency - https://developers.google.com/appengine/docs/python/datastore/structuring_for_strong_consistency and do some searching of SO. This question has been asked many times before.

Retrieve gtalk nickname in python xmpp

In python xmpp module, I'm able to retrieve the nickname of any contacts as follows:
self.connection.auth(userJid.getNode(), self.password)
self.roster = self.connection.getRoster()
name = self.roster.getName(buddyJid)
..where buddyJid is of the form user#gmail.com.
Now, I need to retrieve the nickname of the user who authenticates the connection (userJid). I cannot find the name using the above method.
Which method can I use retrieve the name of the current user?
This information is not in the roster. You will need to query the clients individually and get their vCard by sending this IQ :
<iq from='stpeter#jabber.org/roundabout'
id='v1'
type='get'>
<vCard xmlns='vcard-temp'/>
</iq>
Thank you nicholas_o, this is a sample function I put together based your suggestion. (The XML logic isn't ideal, but it was sufficient for the simple task I needed this for)
def vcard(disp, jid):
msg = xmpp.protocol.Iq()
msg.setType('get')
msg.setTo(jid)
qc = msg.addChild('vCard')
qc.setAttr('xmlns', 'vcard-temp')
rep = disp.SendAndWaitForResponse(msg)
# to see what other fields are available in the XML output:
# print rep
userid=fname=lname=title=department=region=None
for i in rep.getChildren():
for j in i.getChildren():
if j.getName() == "TITLE":
title = j.getData().encode('utf-8')
for k in j.getChildren():
if k.getName() == "GIVEN":
fname = k.getData().encode('utf-8')
if k.getName() == "FAMILY":
lname = k.getData().encode('utf-8')
if k.getName() == "ORGUNIT":
department = k.getData().encode('utf-8')
if k.getName() == "REGION":
region = k.getData().encode('utf-8')
return fname, lname, title, department, region

Categories

Resources