Python Forum
When I print a key from dict it prints it but when I try to assign it to a variable I
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
When I print a key from dict it prints it but when I try to assign it to a variable I
#1
Here is my code and expected output:

    from __future__ import print_function
    import pickle
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    import json
    from re import search
    import base64

    SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
    def auth():
        creds = None
        if os.path.exists('token.pickle'):
            with open ('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    'credentials.json', SCOPES)
                creds = flow.run_local_server(port=0)
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
        service = build('gmail', 'v1', credentials=creds)
        return(service)

    def getMessages(service):
        results = service.users().messages().list(userId='me', labelIds=['UNREAD','Label_8']).execute()
        messages = results.get('messages', [])
        guest_emails=[]
        if not messages:
            print('No messages found.')
        else:
            print('Messages:')
            for message in messages:
                result_mes = service.users().messages().get(userId='me', id=message['id'], format='full').execute()

                result = result_mes['payload']['parts'][0]['body']['data']

                mes_body = base64.b64decode(result).decode("utf-8")
                try:
                    if search('(?<=Email: ).([^\s]+)', mes_body):
                        email = search('(?<=Email: ).([^\s]+)', mes_body)
                        guest_emails.append(email)
                except AssertionError:
                    pass
            print(guest_emails)
The dict that I am getting as a response from the call is:

{'id': '1760839065906ca4', 'threadId': '1760839065906ca4', 'labelIds': ['UNREAD', 'Label_8', 'CATEGORY_UPDATES'], 'snippet': 'New reservation Booking Customer: Patrick Amstutz Email: [email protected] Phone: +41 786451602 Reservation n. 2638032415 made on 27/11/2020 06:39:29 Reservation summary: Arrival: 05/04/', 'payload': {'partId': '', 'mimeType': 'multipart/alternative', 'filename': '', 'headers': [{'name': 'Delivered-To', 'value': '[email protected]'}, {'name': 'Received', 'value': 'by 2002:a05:6a10:6c1:0:0:0:0 with SMTP id c1csp1155930pxv;        Thu, 26 Nov 2020 21:42:04 -0800 (PST)'}, {'name': 'X-Google-Smtp-Source', 'value': 'ABdhPJwP4uWsTIFOWxR8GRuBk5ScoLQG6Xmd9hCyrIWqlTIVhf6eZzv0quvoVMaLGwG1U4kaMwWQ'}, {'name': 'X-Received', 'value': 'by 2002:a1c:7e11:: with SMTP id z17mr6884757wmc.83.1606455723910;        Thu, 26 Nov 2020 21:42:03 -0800 (PST)'}, {'name': 'ARC-Seal', 'value': 'i=1; a=rsa-sha256; t=1606455723; cv=none;        d=google.com; s=arc-20160816;        b=CY5LfIMprU1vXJpEPeYnbanngwcpMITGGI665ilXHKDTL3UqMSYHP929+rTDujMfQL         IE9N4YuoV/pmVHXjxXMwMdjYDaTWQLGEQZ5AL3H2QW1O6MRC5qEh0h0ExUjDyePmBV6F         o2SxojpjoXB3pWHdcmqBMngMjubjWhgqbFICy5xkfkft+HGOSRCGSlPg7Ga1cKfvp/Yy         N6ARXq4Qxx30vtXreSjiUQz81bWIsvqdCOfjn5N2e8e6VYhXlHr7fxEaK7zjKaWNS/BM         APUXBct5Sbf2eQJRdmyxAFBZejHZT0ronhvhMKi4tpAqhEbMEVUy2raOkekNb8Mx+IK/         RS5g=='}, {'name': 'ARC-Message-Signature', 'value': 'i=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=arc-20160816;        h=content-transfer-encoding:message-id:subject:reply-to:from:to         :dkim-signature:dkim-filter:date;        bh=0fS031IapzXSpk1WEXHMadkHMVnHE2Yl+F+qwSevZac=;        b=efHmR1uzqyyyYc7PB2+0f56C1cAWpLyhUj06m7/vX47Lu0mgbZB+E6LZcegcmZ3/h4         lTLZhfbYAD+kkTSwLJQBBkSmYm23LsxAb7FxY11amM+TxaL2Fp/rJkr4XbfIuxx71ZIX         hd4OCGVIgVNMtatykc0HK4OCWYdlT+W4a5wvyEYB8CnnHTJMMSG9xvTXMRKl2ltyvOr5         VPacZtwfZ77FW1MEjnMcp3B3zidwCptJerWV5fZXqu2PmoVA6xhNLPMQ+3xVgA+pd5/W         z4b8pT5sPFx+bg4P+0n4Z7qf4LVEAmi7gkkL8MVmTBCPZSElvHyek/2p466sSgQOMnGx         nZMg=='}, {'name': 'ARC-Authentication-Results', 'value': 'i=1; mx.google.com;       dkim=pass [email protected] header.s=default header.b=UMJH4ho1;       spf=pass (google.com: domain of [email protected] designates 212.237.48.102 as permitted sender) [email protected];       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=krossbooking.com'}, {'name': 'Return-Path', 'value': '<[email protected]>'}, {'name': 'Received', 'value': 'from krossmail.krossbooking.com (krossmail.krossbooking.com. [212.237.48.102])        by mx.google.com with ESMTPS id j65si7800376wma.123.2020.11.26.21.42.03        for <[email protected]>        (version=TLS1_2 cipher=ECDHE-ECDSA-AES128-GCM-SHA256 bits=128/128);        Thu, 26 Nov 2020 21:42:03 -0800 (PST)'}, {'name': 'Received-SPF', 'value': 'pass (google.com: domain of [email protected] designates 212.237.48.102 as permitted sender) client-ip=212.237.48.102;'}, {'name': 'Authentication-Results', 'value': 'mx.google.com;       dkim=pass [email protected] header.s=default header.b=UMJH4ho1;       spf=pass (google.com: domain of [email protected] designates 212.237.48.102 as permitted sender) [email protected];       dmarc=pass (p=NONE sp=NONE dis=NONE) header.from=krossbooking.com'}, {'name': 'Date', 'value': 'Fri, 27 Nov 2020 06:42:02 +0100'}, {'name': 'DKIM-Filter', 'value': 'OpenDKIM Filter v2.11.0 krossmail.krossbooking.com B82281855B84'}, {'name': 'DKIM-Signature', 'value': 'v=1; a=rsa-sha256; c=relaxed/simple; d=krossbooking.com; s=default; t=1606455721; bh=0fS031IapzXSpk1WEXHMadkHMVnHE2Yl+F+qwSevZac=; h=To:From:Reply-To:Subject:From; b=UMJH4ho1Ohf6DaeuWUQkW/ll/7G6Y/ByeuLxp+IcZyF35qiFbgxnCKE1nOrTSeLtU\t nuGmjnYE1QmdZ+L2co5Ku+159s3Mqse44NNDGGd4JyclFuhVwJjkBcvFIk0R+KHx+g\t +Z31oA42nAwzyxtVXldVFm+NSxA+eJwz37sqFkv8='}, {'name': 'To', 'value': '[email protected]'}, {'name': 'From', 'value': 'Kross Booking <[email protected]>'}, {'name': 'Reply-To', 'value': 'Kross Booking <[email protected]>'}, {'name': 'Subject', 'value': 'New Reservation Booking.com - 2638032415 - ALTIDO Portugal'}, {'name': 'Message-ID', 'value': '<[email protected]>'}, {'name': 'Content-Type', 'value': 'multipart/alternative; boundary="b1_caee68f9abaf4b57fd614842ab7bf304"'}, {'name': 'Content-Transfer-Encoding', 'value': '8bit'}], 'body': {'size': 0}, 'parts': [{'partId': '0', 'mimeType': 'text/plain', 'filename': '', 'headers': [{'name': 'Content-Type', 'value': 'text/plain; charset=us-ascii'}], 'body': {'size': 602, 'data': 'TmV3IHJlc2VydmF0aW9uIEJvb2tpbmcNCg0KQ3VzdG9tZXI6IFBhdHJpY2sgQW1zdHV0eg0KDQpFbWFpbDogcGFtc3R1LjI2NjAzOUBndWVzdC5ib29raW5nLmNvbQ0KDQpQaG9uZTogKzQxIDc4NjQ1MTYwMg0KDQpSZXNlcnZhdGlvbiBuLiAyNjM4MDMyNDE1IG1hZGUgb24gMjcvMTEvMjAyMCAwNjozOToyOQ0KDQpSRVNFUlZBVElPTiBTVU1NQVJZOg0KDQpBUlJJVkFMOiAwNS8wNC8yMDIxIC0gREVQQVJUVVJFOiAxMS8wNC8yMDIxDQoNClRPVEFMIEZBUkU6IEV1cm8gNTU4LDY1DQoNCkdVRVNUUzogMg0KDQpTVEFUVVM6IENvbmZpcm1lZA0KDQpSRVNFUlZBVElPTiBGT1I6IDEgeCBBTFRJRE8gQ2hpYWRvIFNlbGYgQ2hlY2stSW4gMi1CUiBGbGF0IHcvUGFya2luZyAtDQpTdGFuZGFyZCByYXRlDQoNCkFTU0lHTkVEIFJPT01TOiBBTFRJRE8gQ2hpYWRvIFNlbGYgQ2hlY2stSW4gMi1CUi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IGZyZWUgcGFya2luZy4gKGJhc2VkIG9uIGF2YWlsYWJpbGl0eSkgYWR1bHQ6IDINCg0KDQo=
and this is getting printed when I use:

print(result_mes['payload']['part'][0]['body']['data'])
But get a KeyError: 'data' when I try to do:

result = result_mes['payload']['part'][0]['body']['data']
Here is the output when I run the script:

Error:
C:\Users\user\PythonApps\EmailsReader\EmailsReaderV2>python EmailsReader2.py Messages: Traceback (most recent call last): File "C:\Users\user\PythonApps\EmailsReader\EmailsReaderV2\EmailsReader2.py", line 82, in <module> getMessages(service) File "C:\Users\user\PythonApps\EmailsReader\EmailsReaderV2\EmailsReader2.py", line 49, in getMessages result = result_mes['payload']['parts'][0]['body']['data'] KeyError: 'data'
What is interesting is that when I made a new script and just assigned the dict that I am getting back from the GMAIL API to a dict and tried to do the same operation it worked without a problem. Any suggestions?
Reply
#2
I observe that error raised on line 82 and your snippet has 49 rows. And row # 49 in your snippet is not matching description in error.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Hi,

Yes, on row 89 was my call of the function like this:

88. service = auth()
89. getMessages(service)

It was saying row 49 because I had some commented lines where I tried different things and I just did not include them in the snipper I've posted here as there was no sense. Row 49 was as the error message says and indeed the line where I am trying to assign the dict value to a variable.

Let me know if you have more questions. I really hope we can find out what the issue is.
Reply
#4
Aaaand it turns out I am a stupid moron. It works, it just gets to the end of the data and gives an error as it is empty. I've managed to fix it by just adding a try - except statement. If someone is more interested, let me know.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  variable prints without being declared. ClockPillow 2 323 Jul-11-2021, 12:13 AM
Last Post: ClockPillow
  Try/Exept prints only ones tester_V 11 998 Nov-03-2020, 02:38 AM
Last Post: tester_V
  Print variable values from a list of variables xnightwingx 3 817 Sep-01-2020, 02:56 PM
Last Post: deanhystad
  How to assign a module to a variable even if it's not defined? mandaxyz 5 1,129 Aug-12-2020, 10:34 PM
Last Post: snippsat
  Print part of a variable rs74 4 962 Jul-27-2020, 04:39 PM
Last Post: rs74
  Create, assign and print variables in loop steven_tr 10 1,677 May-28-2020, 04:26 PM
Last Post: ndc85430
  Sort a dict in dict cherry_cherry 4 1,196 Apr-08-2020, 12:25 PM
Last Post: perfringo
  How to print variable name? mayadob 11 3,952 Oct-21-2019, 01:34 AM
Last Post: ichabod801
  Visual Studio Code does not print desired output but only prints "..." vincentolivers 11 3,860 Sep-09-2019, 12:58 PM
Last Post: vincentolivers
  zip file variable prints <zipfile.ZipFile object at 0x7f83fd13bd90> ? Rsh 9 1,669 Jun-27-2019, 02:00 PM
Last Post: Rsh

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020