Python Microsoft图形API

时间:2019-11-13 20:07:47

标签: python api loops graph

我正在使用Microsoft graph API在python中提取我的电子邮件,并将它们作为json对象返回。有一个限制,它只能返回12封电子邮件。代码是:

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

我得到的回复是十二封电子邮件,其中包含主题和发件人,以及电子邮件的总数。 现在,我想遍历电子邮件,更改query_params中的skip以获得下一个12。有关如何使用循环或递归对其进行遍历的任何方法。

1 个答案:

答案 0 :(得分:0)

我在想一些类似的事情:

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

可能需要进行一些调整,但实际上每次只要向偏移量添加12,只要它不返回错误即可。然后将json附加到列表中并返回。

如果您知道有多少封电子邮件,也可以用这种方式进行批量处理。