我正在使用 google gmail api 库在 python 中编写一个 gmail 数据查询项目,并且我正在使用 Gmail API credentials.json 文件。
如何将我的凭据存储在私有环境中,以便当其他人使用我的脚本时,他们不会自动使用我的 gmail credentials.json。
这是我尝试过的。在我的 .env 文件中,我创建了一个变量 CRED
CRED={"installed":{"client_id":"##########-#########.apps.googleusercontent.com","project_id":"email-query-#######","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"#############################","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
此后,我编写了以下代码:
from __future__ import print_function
import os
import os.path
from googleapiclient.discovery import build
import httplib2
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def main():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
config = json.loads(os.environ['CRED'])
flow = InstalledAppFlow.from_client_config(config, SCOPES)
creds = flow.run_local_server(port=0)
#Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
http = httplib2.Http()
http = creds.authorize(http)
service = build('gmail', 'v1', http=http) #
# Call the Gmail API to fetch INBOX
results = service.users().messages().list(userId='me',labelIds = ['INBOX']).execute()
messages = results.get('messages', [])
运行代码后,我收到以下错误:
<ipython-input-16-d58887cf8862> in <module>
106
107 if __name__ == '__main__':
--> 108 main()
<ipython-input-16-d58887cf8862> in main()
15 #creds = flow.run_local_server(port=0)
16
---> 17 config = json.loads(os.environ['CRED'])
18 flow = InstalledAppFlow.from_client_config(config, SCOPES)
19 creds = flow.run_local_server(port=0)
~/anaconda3/lib/python3.7/os.py in __getitem__(self, key)
677 except KeyError:
678 # raise KeyError with the original key value
--> 679 raise KeyError(key) from None
680 return self.decodevalue(value)
681
KeyError: 'CRED'
我还要指出,在运行代码之前,我从工作目录中删除了 credentials.json。
还有一件事,如果我将 credentials.json 文件留在工作目录中并运行脚本,我会收到错误消息:
23
24 http = httplib2.Http()
---> 25 http = creds.authorize(http)
26 service = build('gmail', 'v1', http=http) #
27 # Call the Gmail API to fetch INBOX
AttributeError: 'Credentials' object has no attribute 'authorize'
我应该怎么办?