当前位置: 首页>>代码示例>>Python>>正文


Python BatchHttpRequest.execute方法代码示例

本文整理汇总了Python中googleapiclient.http.BatchHttpRequest.execute方法的典型用法代码示例。如果您正苦于以下问题:Python BatchHttpRequest.execute方法的具体用法?Python BatchHttpRequest.execute怎么用?Python BatchHttpRequest.execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在googleapiclient.http.BatchHttpRequest的用法示例。


在下文中一共展示了BatchHttpRequest.execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_http_errors_passed_to_callback

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_http_errors_passed_to_callback(self):
    batch = BatchHttpRequest()
    callbacks = Callbacks()
    cred_1 = MockCredentials('Foo')
    cred_2 = MockCredentials('Bar')

    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_RESPONSE_WITH_401),
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_RESPONSE_WITH_401),
      ])

    creds_http_1 = HttpMockSequence([])
    cred_1.authorize(creds_http_1)

    creds_http_2 = HttpMockSequence([])
    cred_2.authorize(creds_http_2)

    self.request1.http = creds_http_1
    self.request2.http = creds_http_2

    batch.add(self.request1, callback=callbacks.f)
    batch.add(self.request2, callback=callbacks.f)
    batch.execute(http=http)

    self.assertEqual(None, callbacks.responses['1'])
    self.assertEqual(401, callbacks.exceptions['1'].resp.status)
    self.assertEqual(
        'Authorization Required', callbacks.exceptions['1'].resp.reason)
    self.assertEqual({u'baz': u'qux'}, callbacks.responses['2'])
    self.assertEqual(None, callbacks.exceptions['2'])
开发者ID:Acidburn0zzz,项目名称:google-api-python-client,代码行数:36,代码来源:test_http.py

示例2: test_execute_initial_refresh_oauth2

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_execute_initial_refresh_oauth2(self):
    batch = BatchHttpRequest()
    callbacks = Callbacks()
    cred = MockCredentials('Foo')

    # Pretend this is a OAuth2Credentials object
    cred.access_token = None

    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_SINGLE_RESPONSE),
    ])

    cred.authorize(http)

    batch.add(self.request1, callback=callbacks.f)
    batch.execute(http=http)

    self.assertEqual({'foo': 42}, callbacks.responses['1'])
    self.assertIsNone(callbacks.exceptions['1'])

    self.assertEqual(1, cred._refreshed)

    self.assertEqual(1, cred._authorized)

    self.assertEqual(1, cred._applied)
开发者ID:CleverChuk,项目名称:google-api-python-client,代码行数:29,代码来源:test_http.py

示例3: get_messages

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
def get_messages(contactId):
    contact = session['seen'][contactId]
    credentials = client.OAuth2Credentials.from_json(session['credentials'])
    http = credentials.authorize(httplib2.Http(cache=".cache"))

# Build the Gmail service from discovery

    gmail_service = discovery.build('gmail', 'v1', http=http)
    def mailscallbackfunc(result, results, moreresults):
        # in old Python versions:
        # if seen.has_key(marker)
        # but in new ones:
        if 'UNREAD' in results['labelIds']:
            Unread = 'true'
        else:
            Unread = 'false'
        for header in results['payload']['headers']:
            if header['name'] == 'Date':
                Date = header['value']
            if header['name'] == 'From':
                From = header['value']
                if From == "Anders Damsgaard <[email protected]>": #SKAL ÆNDRES
                    Sent = True
                else:
                    Sent = False
            if header['name'] == 'Subject':
                Subject = header['value']

        Contact = {
            'messageId': results['id'],
            'date': Date,
            'subject': Subject,
            'snippet': results['snippet'],
            'unread': Unread,
            'sent': Sent
            }

        session['mails'].append(Contact)

    #for msg_id in message_ids['messages']:
    #    batchContacts.add(gmail_service.users().messages().get(userId='me',
    #              id=msg_id['id'], format='metadata',
    #              metadataHeaders=['from', 'date']))
    #batchContacts.execute()

    query = "\"to:'" + contact + "' AND from:me \" OR from:'" + contact + "'"
    message_ids = gmail_service.users().messages().list(userId='me',
            maxResults=10, labelIds='INBOX', q=query).execute()

    batchMails = BatchHttpRequest(callback=mailscallbackfunc)

    for msg_id in message_ids['messages']:
        batchMails.add(gmail_service.users().messages().get(userId='me',
                  id=msg_id['id'], format='metadata',
                  metadataHeaders=['from', 'date', 'subject']))
    batchMails.execute()
    response = {'messages': session['mails']}
    js = json.dumps(response)
    resp = Response(js, status=200, mimetype='application/json')
    return resp
开发者ID:andersdm,项目名称:emailody-stage,代码行数:62,代码来源:app.py

示例4: get_mailslist

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
    def get_mailslist(message_ids, result, index, credentials):
        mails = []

        def mailscallbackfunc(result, results, moreresults):
            # in old Python versions:
            # if seen.has_key(marker)
            # but in new ones:
            if "UNREAD" in results["labelIds"]:
                Unread = "true"
            else:
                Unread = "false"
            for header in results["payload"]["headers"]:
                if header["name"] == "Date":
                    Date = header["value"]
                if header["name"] == "From":
                    From = header["value"]
                    if From == "Anders Damsgaard <[email protected]>":  # SKAL ÆNDRES
                        Sent = True
                    else:
                        Sent = False
                if header["name"] == "Subject":
                    Subject = header["value"]

            Contact = {
                "id": result,
                "messageId": results["id"],
                "date": Date,
                "subject": Subject,
                "snippet": results["snippet"],
                "unread": Unread,
                "sent": Sent,
            }

            mails.append(Contact)

        # for msg_id in message_ids['messages']:
        #    batchContacts.add(gmail_service.users().messages().get(userId='me',
        #              id=msg_id['id'], format='metadata',
        #              metadataHeaders=['from', 'date']))
        # batchContacts.execute()
        credentials = client.OAuth2Credentials.from_json(credentials)
        http = credentials.authorize(httplib2.Http(cache=".cache"))
        # Build the Gmail service from discovery
        gmail_service = discovery.build("gmail", "v1", http=http)
        batchMails = BatchHttpRequest(callback=mailscallbackfunc)
        for msg_id in message_ids["messages"]:
            batchMails.add(
                gmail_service.users()
                .messages()
                .get(userId="me", id=msg_id["id"], format="metadata", metadataHeaders=["from", "date", "subject"])
            )
        batchMails.execute()
        results[index] = mails
        return True
开发者ID:andersdm,项目名称:emailody-stage,代码行数:56,代码来源:app_working.py

示例5: get_mailslist

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
    def get_mailslist(message_ids, result, index, credentials):
        mails = []
        
        def mailscallbackfunc(result, results, moreresults):
            # in old Python versions:
            # if seen.has_key(marker)
            # but in new ones:
            if 'UNREAD' in results['labelIds']:
                Unread = 'true'
            else:
                Unread = 'false'
            for header in results['payload']['headers']:
                if header['name'] == 'Date':
                    Date = header['value']
                if header['name'] == 'From':
                    From = header['value']
                    if From == "Anders Damsgaard <[email protected]>": #SKAL ÆNDRES
                        Sent = True
                    else:
                        Sent = False
                if header['name'] == 'Subject':
                    Subject = header['value']

            Contact = {
                'id': result,
                'messageId': results['id'],
                'date': Date,
                'subject': Subject,
                'snippet': results['snippet'],
                'unread': Unread,
                'sent': Sent
                }

            mails.append(Contact)

        #for msg_id in message_ids['messages']:
        #    batchContacts.add(gmail_service.users().messages().get(userId='me',
        #              id=msg_id['id'], format='metadata',
        #              metadataHeaders=['from', 'date']))
        #batchContacts.execute()
        credentials = client.OAuth2Credentials.from_json(credentials)
        http = credentials.authorize(httplib2.Http(cache=".cache"))
        # Build the Gmail service from discovery
        gmail_service = discovery.build('gmail', 'v1', http=http)
        batchMails = BatchHttpRequest(callback=mailscallbackfunc)
        for msg_id in message_ids['messages']:
            batchMails.add(gmail_service.users().messages().get(userId='me',
                      id=msg_id['id'], format='metadata',
                      metadataHeaders=['from', 'date', 'subject']))
        batchMails.execute()
        results[index] = mails
        return True
开发者ID:andersdm,项目名称:emailody-stage,代码行数:54,代码来源:app.py

示例6: test_execute_global_callback

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_execute_global_callback(self):
    callbacks = Callbacks()
    batch = BatchHttpRequest(callback=callbacks.f)

    batch.add(self.request1)
    batch.add(self.request2)
    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_RESPONSE),
      ])
    batch.execute(http=http)
    self.assertEqual({'foo': 42}, callbacks.responses['1'])
    self.assertEqual({'baz': 'qux'}, callbacks.responses['2'])
开发者ID:Acidburn0zzz,项目名称:google-api-python-client,代码行数:16,代码来源:test_http.py

示例7: delete_bucket_content

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
    def delete_bucket_content(self, bucket):
        '''Delete content of existing bucket.
        :param bucket: Name of the bucket in google storage to access
        :type bucket: str
        :retunrs: Response JSON str
        :rtype: json
        '''

        objects = self.list_bucket_content(bucket)
        if objects:
            logger.info("Createing batch for objects deletion...")
            batch = BatchHttpRequest(callback=self.delete_object_cb)
            for o in objects:
                logger.debug(
                    "Adding 'delete request' to batch: %s" % o['name']
                )
                batch.add(self.service.objects().delete(
                    object=o['name'], bucket=bucket
                ))
            logger.info("Executing batch...")
            resp = batch.execute(http=self.http_auth)
            logger.info("Response content from batch: %s" % resp)

            return resp

        return None
开发者ID:fratczakz,项目名称:google_storage_wrapper,代码行数:28,代码来源:utils.py

示例8: test_execute_batch_http_error

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_execute_batch_http_error(self):
    callbacks = Callbacks()
    batch = BatchHttpRequest(callback=callbacks.f)

    batch.add(self.request1)
    batch.add(self.request2)
    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_ERROR_RESPONSE),
      ])
    batch.execute(http=http)
    self.assertEqual({'foo': 42}, callbacks.responses['1'])
    expected = ('<HttpError 403 when requesting '
        'https://www.googleapis.com/someapi/v1/collection/?foo=bar returned '
        '"Access Not Configured">')
    self.assertEqual(expected, str(callbacks.exceptions['2']))
开发者ID:Acidburn0zzz,项目名称:google-api-python-client,代码行数:19,代码来源:test_http.py

示例9: test_execute_refresh_and_retry_on_401

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_execute_refresh_and_retry_on_401(self):
    batch = BatchHttpRequest()
    callbacks = Callbacks()
    cred_1 = MockCredentials('Foo')
    cred_2 = MockCredentials('Bar')

    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_RESPONSE_WITH_401),
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
       BATCH_SINGLE_RESPONSE),
      ])

    creds_http_1 = HttpMockSequence([])
    cred_1.authorize(creds_http_1)

    creds_http_2 = HttpMockSequence([])
    cred_2.authorize(creds_http_2)

    self.request1.http = creds_http_1
    self.request2.http = creds_http_2

    batch.add(self.request1, callback=callbacks.f)
    batch.add(self.request2, callback=callbacks.f)
    batch.execute(http=http)

    self.assertEqual({'foo': 42}, callbacks.responses['1'])
    self.assertEqual(None, callbacks.exceptions['1'])
    self.assertEqual({'baz': 'qux'}, callbacks.responses['2'])
    self.assertEqual(None, callbacks.exceptions['2'])

    self.assertEqual(1, cred_1._refreshed)
    self.assertEqual(0, cred_2._refreshed)

    self.assertEqual(1, cred_1._authorized)
    self.assertEqual(1, cred_2._authorized)

    self.assertEqual(1, cred_2._applied)
    self.assertEqual(2, cred_1._applied)
开发者ID:Acidburn0zzz,项目名称:google-api-python-client,代码行数:43,代码来源:test_http.py

示例10: test_execute_request_body

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
  def test_execute_request_body(self):
    batch = BatchHttpRequest()

    batch.add(self.request1)
    batch.add(self.request2)
    http = HttpMockSequence([
      ({'status': '200',
        'content-type': 'multipart/mixed; boundary="batch_foobarbaz"'},
        'echo_request_body'),
      ])
    try:
      batch.execute(http=http)
      self.fail('Should raise exception')
    except BatchError, e:
      boundary, _ = e.content.split(None, 1)
      self.assertEqual('--', boundary[:2])
      parts = e.content.split(boundary)
      self.assertEqual(4, len(parts))
      self.assertEqual('', parts[0])
      self.assertEqual('--', parts[3].rstrip())
      header = parts[1].splitlines()[1]
      self.assertEqual('Content-Type: application/http', header)
开发者ID:Acidburn0zzz,项目名称:google-api-python-client,代码行数:24,代码来源:test_http.py

示例11: summarize_mail

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
def summarize_mail():

    service, http = authorize_me()
    batch = BatchHttpRequest()

    response = service.users().messages().list(userId=constants.USER_ID, q=constants.DEFAULT_QUERY).execute()
    messages = response.get('messages', [])


    if messages:
        # TODO think this only gets the first few, might need to page through results

        for message in messages:
            request = service.users().messages().get(userId=constants.USER_ID, id=message['id'], format=constants.RESPONSE_FORMAT, metadataHeaders=[constants.FROM_HEADER, constants.TO_HEADER])

            batch.add(request, callback=parse_mail)

        batch.execute(http=http)


        print "There are %s unread messages in your inbox." % len(summary.messages)

        print "%s of them are marked as important and %s are addressed to you." % (summary.important, summary.addressed_to_me)

        print "%s of them are scary." % summary.flagged

        response = raw_input("\nYou can do the thing! Do you want to see a preview of your messages? ")

        if response.lower().startswith('y'):
            print "\n"
            for i, msg in enumerate(summary.messages):
                print "Message #%s" % i
                print "=" * 30
                print "From: %s\nTo: %s\nSubject: %s" % (msg.sender, msg.to, msg.snippet)
                print "=" * 30
                print "\n"
    else:
        print "No messages! You are free. :)"
开发者ID:trustrachel,项目名称:peacemail,代码行数:40,代码来源:check.py

示例12: contacts

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
def contacts(pagenr):
    # Authorize the httplib2.Http object with our credentials	
    credentials = client.OAuth2Credentials.from_json(session['credentials'])
    
    http = credentials.authorize(httplib2.Http(cache=".cache"))

# Build the Gmail service from discovery

    gmail_service = discovery.build('gmail', 'v1', http=http)
    while (len(session['seen'])+1 < pagenr*10):
        
# Retrieve a page of threads

        

# Print ID for each thread
# if threads['threads']:
#  for thread in threads['threads']:
#    print 'Thread ID: %s' % (thread['id'])

        def contactscallbackfunc(result, results, moreresults):
        
       # in old Python versions:
       # if seen.has_key(marker)
       # but in new ones:

            if 'UNREAD' in results['labelIds']:
                Unread = 'true'
            else:
                Unread = 'false'
            for header in results['payload']['headers']:
                if header['name'] == 'Date':
                    Date = header['value']
                if header['name'] == 'From':
                    From = header['value']
                    address = From.split()[-1]
                    address = re.sub(r'[<>]', '', address)
                    Address = address.strip()
                    Name = From.rsplit(' ', 1)[0]
                    From = From.replace('\"','')

                    Name = Name.replace('\"','')
                
                

            if From not in session['seen']:
                Contact = {
                    'id': len(session['seen']),
                    'date': Date,
                    'name': Name,
                    'address': Address,
                    'snippet': results['snippet'],
                    'unread': Unread
                    }
                session['contacts'].append(Contact)
                session['seen'].append(From)
        
        message_ids = gmail_service.users().messages().list(userId='me', maxResults=50, labelIds='INBOX', pageToken=session['contactsNextPageToken']).execute()
        batchContacts = BatchHttpRequest(callback=contactscallbackfunc)
        #return message_ids['messages'][0]['id']
        session['contactsNextPageToken'] = message_ids['nextPageToken']
        for msg_id in message_ids['messages']:
            batchContacts.add(gmail_service.users().messages().get(userId='me', id=msg_id['id'], format='metadata', metadataHeaders=['from', 'date']))
        batchContacts.execute()
        
        

    #return "test"


    #def mailscallbackfunc(result, results, moreresults):
    #    if 'UNREAD' in results['labelIds']:
    #        Unread = 'true'
    #   else:
    #        Unread = 'false'
    #
    #batchMails = BatchHttpRequest(callback=mailscallbackfunc)
    #for contact in session['seen']:
	#	batchContacts.add(gmail_service.users().messages().get(userId='me',
    #              id=msg_id['id'], format='metadata',
    #              metadataHeaders=['from', 'date']))
    #batchMails.execute()
    if pagenr - 1 == 0:
        start = 0
        end = 10
    else:
        start = (pagenr - 1) * 10 -1 
        end = pagenr * 10 -1
    response = {'nextPageToken': session['contactsNextPageToken'], 'contacts': session['contacts'][start:end]} 
    js = json.dumps(response)
    resp = Response(js, status=200, mimetype='application/json')
    return resp
开发者ID:andersdm,项目名称:emailody-stage,代码行数:94,代码来源:app.py

示例13: get_messages

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
def get_messages(contactId):
    contact = session['seen'][contactId]
    contact_address = contact.split()[-1]
    contact_address = re.sub(r'[<>]', '', contact_address)
    contact_address = contact_address.strip()
    credentials = client.OAuth2Credentials.from_json(session['credentials'])
    http = credentials.authorize(httplib2.Http(cache='.cache'))

# Build the Gmail service from discovery

    gmail_service = discovery.build('gmail', 'v1', http=http)

    def mailscallbackfunc(result, results, moreresults):
        if 'labelIds' in results:
            if 'UNREAD' in results['labelIds']:
                Unread = True
            else:
                Unread = False
        else:
            Unread = None

        for header in results['payload']['headers']:
            if header['name'].lower() == 'date':
                Date = header['value']
            if header['name'].lower() == 'from':
                From = header['value']
                from_address = From.split()[-1]
                from_address = re.sub(r'[<>]', '', from_address)
                from_address = from_address.strip()
                if from_address.lower() == session['user_address']:
                    Sent = True
                else:
                    Sent = False
            if header['name'].lower() == 'subject':
                Subject = header['value']
        try:
            Subject # does a exist in the current namespace
        except NameError:
            Subject = 'Unknown Subject' # nope

        Contact = {
            'messageId': results['id'],
            'date': Date,
            'subject': Subject,
            'snippet': results['snippet'],
            'unread': Unread,
            'sent': Sent,
            }

        session['mails'].append(Contact)

    query = "(from:me to:" + contact_address + ") OR (from:" + contact + ")"
    print "#######query############"
    print query
    message_ids = gmail_service.users().messages().list(userId='me',
            maxResults=10, q=query).execute()
    #labelIds='INBOX',
    batchMails = BatchHttpRequest(callback=mailscallbackfunc)

    for msg_id in message_ids['messages']:
        batchMails.add(gmail_service.users().messages().get(userId='me'
                       , id=msg_id['id'], format='metadata',
                       metadataHeaders=['from', 'date', 'subject']))
    batchMails.execute()
    response = {'messages': session['mails']}
    js = json.dumps(response)
    resp = Response(js, status=200, mimetype='application/json')
    return resp
开发者ID:andersdm,项目名称:emailody-stage,代码行数:70,代码来源:flask_app.py

示例14: __init__

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
class GoogleCalendar:

    _scope = 'https://www.googleapis.com/auth/calendar'

    def __init__(self, key_p12_path, service_account_mail):

        if not os.path.exists(key_p12_path):
            raise AttributeError('p12 key path is not vaild')

        f = file(key_p12_path, 'rb')
        key = f.read()
        f.close()

        credentials = SignedJwtAssertionCredentials(
            service_account_mail,
            key,
            scope=self._scope)

        http = httplib2.Http()
        self._http = credentials.authorize(http)
        self._service = build('calendar', 'v3', http=http)
        # batch is limited up to 1000 queries in one
        self._batch = BatchHttpRequest()
        self._calendar_id = None
        self._event_json_path = None
        self._event_name_to_id_dict = None
        self._service_mail = service_account_mail

    def pushChanges(self):
        self._batch.execute(http=self._http)

    def eventAdded(self, request_id, response, exception):

        if exception is None:
            self._event_name_to_id_dict[request_id] = response['id']
        else:
            pass  # TODO add log message

    def eventModified(self, request_id, response, exception):
        if exception is None:
            self._event_name_to_id_dict[request_id] = response['id']
        else:
            pass  # TODO add log message

    def _convertDateTime(self, date, time):
        return rfc3339.rfc3339(datetime.datetime(int(date[:4]),
                                                 int(date[5:7]),
                                                 int(date[8:10]),
                                                 int(time[:2]),
                                                 int(time[3:5])))

    def _eventStartDateTime(self, event_details):
        return self._convertDateTime(event_details[u'Data rozpoczęcia'.encode('windows-1250')],
                                     event_details[u'Czas rozpoczęcia'.encode('windows-1250')])

    def _eventEndDateTime(self, event_details):
        return self._convertDateTime(event_details[u'Data zakończenia'.encode('windows-1250')],
                                     event_details[u'Czas zakończenia'.encode('windows-1250')])

    def _eventLocation(self, event_details):
        return event_details[u'Lokalizacja'.encode('windows-1250')]

    def addScheduleEvents(self, event_names, event_details):

        for ev_name in event_names:
            ev_det = event_details[ev_name]

            event = {
                'summary': ev_name.decode('windows-1250'),

                'start': {
                    'dateTime': self._eventStartDateTime(ev_det)
                },
                'end': {
                    'dateTime': self._eventEndDateTime(ev_det)
                },
            }

            loc = self._eventLocation(ev_det)
            if loc is not None:
                event['location'] = loc

            if '(w)' in ev_name:
                col = '10'
            elif '(L)' in ev_name:
                col = '4'
            elif '(p)' in ev_name:
                col = '6'
            elif u'(ć)'.encode('windows-1250') in ev_name:
                col = '11'
            else:
                col = '1'

            event['colorId'] = col
            self._batch.add(self._service.events().insert(calendarId=self._calendar_id,
                                                          body=event), callback=self.eventAdded, request_id=ev_name)

    def modifyScheduleEvents(self, event_names, new_event_details):

        for ev_name in event_names:
#.........这里部分代码省略.........
开发者ID:jbylina,项目名称:WatEdChanges,代码行数:103,代码来源:GoogleCalendar.py

示例15: get_listmessages

# 需要导入模块: from googleapiclient.http import BatchHttpRequest [as 别名]
# 或者: from googleapiclient.http.BatchHttpRequest import execute [as 别名]
def get_listmessages():
    def get_mailslist(message_ids, result, index, credentials):
        mails = []

        def mailscallbackfunc(result, results, moreresults):
            # in old Python versions:
            # if seen.has_key(marker)
            # but in new ones:
            if "UNREAD" in results["labelIds"]:
                Unread = "true"
            else:
                Unread = "false"
            for header in results["payload"]["headers"]:
                if header["name"] == "Date":
                    Date = header["value"]
                if header["name"] == "From":
                    From = header["value"]
                    if From == "Anders Damsgaard <[email protected]>":  # SKAL ÆNDRES
                        Sent = True
                    else:
                        Sent = False
                if header["name"] == "Subject":
                    Subject = header["value"]

            Contact = {
                "id": result,
                "messageId": results["id"],
                "date": Date,
                "subject": Subject,
                "snippet": results["snippet"],
                "unread": Unread,
                "sent": Sent,
            }

            mails.append(Contact)

        # for msg_id in message_ids['messages']:
        #    batchContacts.add(gmail_service.users().messages().get(userId='me',
        #              id=msg_id['id'], format='metadata',
        #              metadataHeaders=['from', 'date']))
        # batchContacts.execute()
        credentials = client.OAuth2Credentials.from_json(credentials)
        http = credentials.authorize(httplib2.Http(cache=".cache"))
        # Build the Gmail service from discovery
        gmail_service = discovery.build("gmail", "v1", http=http)
        batchMails = BatchHttpRequest(callback=mailscallbackfunc)
        for msg_id in message_ids["messages"]:
            batchMails.add(
                gmail_service.users()
                .messages()
                .get(userId="me", id=msg_id["id"], format="metadata", metadataHeaders=["from", "date", "subject"])
            )
        batchMails.execute()
        results[index] = mails
        return True

    credentials = client.OAuth2Credentials.from_json(session["credentials"])

    http = credentials.authorize(httplib2.Http(cache=".cache"))
    # Build the Gmail service from discovery

    gmail_service = discovery.build("gmail", "v1", http=http)

    def mailIdscallbackfunc(result, results, moreresults):
        session["messageIds"].append(results)

    batchMailIds = BatchHttpRequest(callback=mailIdscallbackfunc)

    for contact in session["seen"][0:10]:
        query = "\"to:'" + contact + "' AND from:me \" OR from:'" + contact + "'"
        batchMailIds.add(gmail_service.users().messages().list(userId="me", maxResults=10, labelIds="INBOX", q=query))
    batchMailIds.execute()

    threads = [None] * 10
    results = [None] * 10

    for i in range(0, 10):
        threads[i] = Thread(target=get_mailslist, args=(session["messageIds"][i], results, i, session["credentials"]))
        threads[i].start()

    for i in range(0, 10):
        threads[i].join()

    js = json.dumps(results)
    resp = Response(js, status=200, mimetype="application/json")
    return resp
开发者ID:andersdm,项目名称:emailody-stage,代码行数:88,代码来源:app_working.py


注:本文中的googleapiclient.http.BatchHttpRequest.execute方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。