python-3.x - 如何在注册过程中获取多个谷歌凭据(Gmail API、Pub/Sub、联系人)

标签 python-3.x oauth-2.0 gmail-api google-contacts-api google-cloud-pubsub

我正在开发一个基于 Python 的项目,该项目可以访问各种 Google API,例如 Google Contacts API、Pub/Sub API、Gmail API 等。

目前,通过 Google API 控制台使用 OAuth 2.0 为这些 API 获取相关 token 和凭据是高度手动的。我想为愿意让我通过上述 API(不仅仅是 Gmail API)管理他们的 Gmail 邮箱的多个用户自动执行此操作。

如何在注册过程中获取所有这些 API 的凭据,以便将凭据 json 文件保存在 db 中,然后管理邮箱? “用谷歌注册”功能只产生一个基本的凭据,我无法弄清楚如何将用户路由到相关页面,我在其中请求他/她允许使用 API 访问邮箱(谷歌联系人、Gmail 和发布/订阅 API)。然后我计划以编程方式在我的 Python 脚本中使用此凭据(对象)..

这是我通过 get_credentials() 创建凭据的脚本。如您所见,我需要首先在 API 控制台上手动获取 client-secret-file,然后使用以下脚本生成 wrt 范围的凭据(这是我需要在注册过程中自动化并获取其他几个凭据的地方)

SCOPES = 'https://www.googleapis.com/auth/gmail.modify'
CLIENT_SECRET_FILE = "client_secret_pubsub.json"
APPLICATION_NAME = "pub-sub-project-te"

def get_credentials():
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 = oauth2client.file.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
    print('Storing credentials to ' + credential_path)
return credentials


def pull_emails_from_mailbox(credentials_obj):

credentials = get_credentials()

http = credentials.authorize(Http())

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

user_id =  'me'
label_id_one = 'INBOX'
label_id_two = 'UNREAD'

# Getting all the unread messages from Inbox
# labelIds can be changed accordingly
messages = GMAIL.users().messages().list(userId=user_id, maxResults=1000).execute()
#unread_msgs = GMAIL.users().messages().list(userId='me',labelIds=[label_id_one,label_id_two]).execute()

# We get a dictonary. Now reading values for the key 'messages'

mssg_list = messages['messages']

print ("Total messages in inbox: ", str(len(mssg_list)))

final_list = []

new_messages=[]
for mssg in mssg_list:
    m_id = mssg['id'] # get id of individual message
    new_messages.append(GMAIL.users().messages().get(userId=user_id, id=m_id).execute()) # fetch the message using API

return new_messages


def prepare_raw_db (raw_messages):

messageId=[]
historyId=[]
raw=[]

print ("Total number of emails to be parsed:", len(raw_messages))

for msg in raw_messages:
    messageId.append(msg["id"])
    historyId.append(msg['historyId'])
    raw.append(msg)

        #'addLabelIds': ['UNREAD']
    GMAIL.users().messages().modify(userId="me", id=msg["id"],body={ 'removeLabelIds': ['UNREAD'] }).execute() 

msg_dict={"messageId":messageId, "historyId":historyId, "raw":raw}

df=pd.DataFrame(msg_dict)

df.raw=df.raw.astype(str)

return df

谢谢

最佳答案

你必须让网络服务器做同样的事情。流程将遵循 -

  1. 用户转到您的网络应用。
  2. 用户点击使用 Google 登录
  3. 用户将被重定向到具有所需范围的 Goole OAuth2 url(在您的情况下,它是 Google Contacts API、Pub/Sub API、Gmail API 等)
  4. 用户将授予访问您在 Google Developer Console 上创建的应用程序的权限。
  5. 它将根据 OAuth2 请求返回具有所需访问权限的应用程序的 token /代码。
  6. 您可以将其存储在某些数据库中,并可以按照 OAuth2 使用它。

以上过程是一步步给出的here .

关于python-3.x - 如何在注册过程中获取多个谷歌凭据(Gmail API、Pub/Sub、联系人),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49775620/

相关文章:

python - 如何根据字典和另一列之间的匹配创建新的 df 列

authentication - 如何管理使用 GitBook 创建的书籍的访问权限?

java - Spring OAuth2 刷新 token

java - 是否可以使用 gmail API 代表用户发送邮件

c# - Gmail API : Watch Inbox label Only

python - pandas如何计算sem()?

python - 有没有一种方法可以在不使用 winsound 的情况下产生特定频率的哔声?

python - Selenium 无法使用正确的 chromedriver 版本和 chrome 版本

java - Spring OAuth2 自定义授权类型 Autowiring 类返回 null

javascript - 如何引用json的属性