【发布时间】:2018-04-17 18:05:27
【问题描述】:
我正在尝试通过推送通知 API 在我的 Gmail 帐户中接收新邮件。 我有一个带有 ssl 证书的服务器,我已经在 Google 中验证了它并添加到我的 Pub/Sub 项目中:
#!/usr/bin/python3
import http.server
import array
import ssl
class CallbackHTTPServer(http.server.HTTPServer):
def server_activate(self):
http.server.HTTPServer.server_activate(self)
class HttpProcessor(http.server.BaseHTTPRequestHandler):
def add_OK_plain_text_header(self):
self.send_response(200)
self.send_header('content-type','text/plain')
self.end_headers()
def do_GET(self):
self.add_OK_plain_text_header()
print("GOT GET REQUEST")
self.wfile.write("OK".encode('utf-8'))
def do_POST(self):
self.add_OK_plain_text_header()
print("GOT POST REQUEST")
self.wfile.write("OK".encode('utf-8'))
def main():
httpd = CallbackHTTPServer(('', 443), HttpProcessor)
httpd.socket = ssl.wrap_socket(httpd.socket, certfile='./server.pem', server_side=True)
httpd.serve_forever()
if __name__ == "__main__":
main()
我还创建了一个主题和订阅推送通知到我的服务器地址(如here 中所述)。 我还按照here 中的描述初始化了 Gmail API,并运行了 Gmail API 监视请求,该请求以正确的 historyId 和过期时间进行响应。 但是即使我通过将消息发布到我的主题来手动创建它们,我的服务器也没有得到任何更新:
#!/usr/bin/python
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/gmail-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Gmail API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'gmail-python-quickstart.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
request = {
'labelIds': ['INBOX'],
'topicName': 'projects/################/topics/#######'
}
print(service.users().watch(userId='me', body=request).execute())
if __name__ == '__main__':
main()
【问题讨论】:
-
检查您是否已授予 Gmail 权限以向您的主题发布通知,Cloud Pub/Sub 需要它。还要仔细检查document 中的每个步骤,看看你是否遗漏了什么。希望这会有所帮助。
-
是的,我授予了向 Gmail 发布通知的权限。我已经完成了您提供的文件的所有步骤。
标签: python ssl push-notification webserver gmail-api