【问题标题】:Using Gmail API without opening browser in Python使用Gmail API而不用Python打开浏览器
【发布时间】:2020-06-26 12:03:35
【问题描述】:

我在 Jetson Xavier 中有无头软件。我正在使用 Gmail API 发送邮件。我的代码在笔记本电脑中正常工作,但是在 Jetson 中禁用了 GUI 服务,无法打开浏览器。因此,当我尝试在 Jetson 中使用 Gmail API 时,身份验证失败。

我已将经过身份验证的“token.pickle”从笔记本电脑复制到 Jetson。它可以在短时间内正常工作。然后,它想要再次进行身份验证。

我该如何解决这个问题? Jetson中如何阻止浏览器打开进行身份验证?

谢谢。

这部分代码用于认证:

class EmailSender:

    def __init__(self):

        # If modifying these scopes, delete the file token.pickle.
        SCOPES = ['https://www.googleapis.com/auth/gmail.compose']

        creds = None
        # The file token.pickle stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        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:
                creds_dir = os.path.dirname(os.path.abspath(__file__)) + '/credentials.json'
                flow = InstalledAppFlow.from_client_secrets_file(
                    creds_dir, 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)

        self.service = build('gmail', 'v1', credentials=creds)

【问题讨论】:

  • 请编辑您的问题并包含您的代码
  • 我已经编辑并包含了代码
  • 浏览器总是需要打开,以便用户能够验证您的代码。请记住,InstalledAppFlow 用于已安装的应用程序,因此它将在运行它的机器上打开浏览器,而不是在作为 Web 应用程序运行时在用户机器上打开它。

标签: python api gmail


【解决方案1】:

很遗憾,出于安全原因,gmail(以及大多数现代身份验证服务)不允许您直接自动登录。为了确保第三方服务不会窃取您的帐户,Google 会要求您作为人类输入您的帐户和密码,并且 Google 会向您尝试登录的服务返回一个 cookie 或令牌。

但是,由于您正在处理自己的项目,并且我假设您知道该程序不会使您的帐户面临风险,因此您可以使用 selenium 模拟浏览器并自动输入您的帐户。您可以参考this post 了解如何操作。

【讨论】:

  • 问题是关于 gmail api 而不是 gmail Web 应用程序
  • 感谢您的回复。我了解安全原因。我接受。我真正的观点是如何阻止浏览器在 Jetson 中打开。因为我有无头软件
  • @redrussianarmy 哦,我误解了你的问题。据我所知,官方 sdk 并没有给你禁用它的方法。但是您可以使用brow.sh 之类的浏览器在无头环境中登录。
  • @whilrun 感谢您的建议。我已经安装了浏览器。但是,它不会在我的程序中自动触发,我无法在“www-browser”中看到它以使其成为默认命令行浏览器。我该如何处理?你有什么主意吗?谢谢
  • @redrussianarmy 您可以使用以下命令在 x-www-browser 中手动添加 browsh sudo update-alternatives --install /usr/bin/x-www-browser x-www-browser $(which browsh) 150。确保没有其他浏览器的优先级高于 150。那么您的浏览器应该是其他程序打开的默认浏览器。
猜你喜欢
  • 2016-05-22
  • 2019-04-12
  • 2021-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 2013-09-09
相关资源
最近更新 更多