【问题标题】:Is there any way I can make PyDrive remember authentication for a user?有什么方法可以让 PyDrive 记住用户的身份验证?
【发布时间】:2016-04-26 11:09:05
【问题描述】:

我使用 Python 和 PyDrive 编写了一个程序。 该程序捕获图像并将其上传到 Google Drive 上的文件夹。 这是我的身份验证和上传的基本代码:

gauth = GoogleAuth()
drive = GoogleDrive(gauth)
file_image = drive.CreateFile({"parents":  [{"kind": "drive#fileLink","id": upload_folder_id}]})
file_image.SetContentFile(imageName) #Set the content to the taken image
file_image.Upload() # Upload it

任何时候我运行它想要验证我的程序。有什么方法可以记住认证吗?

【问题讨论】:

  • 我不这么认为,在 web 界面中记住身份验证是通过 cookie 解决的。
  • 是否可以使用配置文件中的用户名、密码组合登录? (这样我只需要创建一次该配置文件)
  • 是的,这将是一个解决方案。使用 Py 2.x 还是 3.x?
  • 使用eval() 可以吗??
  • 是的没关系(但我没用过)

标签: python google-drive-api pydrive


【解决方案1】:

在 Google Drive 的网络界面中,cookie 用于记住身份验证。我建议每次使用脚本时从配置文件中读取登录信息并登录。你可以使用eval(),但请记住,eval() 是邪恶的:)(如果脚本仅供你使用,没关系)。

示例:

在脚本所在的同一文件夹中创建一个名为 login.conf(或类似文件)的文件。将其放入其中:

{"user": "username", "pass": "password"}

将"username" 和"pasword" 替换为您的真实值,但保留"。在你的脚本中,这样做:

with open("login.conf", "r") as f:
    content = eval(f.read())

username = content["user"]
password = content["pass"]

# Now do login using these two variables

更安全的选择是使用ConfigParser(Python 3.x 中的configparser)。

编辑:

看起来登录 Google 云端硬盘需要在您的脚本目录中有一个名为 client_secrets.json 的文件。如果你有它,请像这样登录:

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

gauth.LoadCredentialsFile("credentials.txt")
if gauth.credentials is None:
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    gauth.Refresh()
else:
    gauth.Authorize()

gauth.SaveCredentialsFile("credentials.txt")

drive = GoogleDrive(gauth)

希望这会有所帮助(问,如果有什么不够清楚)!

【讨论】:

  • 谢谢!我不清楚的另一部分是,我如何使用这些信息登录到我的 Google Drive。 PyDrive 怎么可能?
  • 好的。我从未使用过 PyDrive,但文档说,您需要一个名为 client_secrets.json 的文件。你有吗?
  • 是的,这是我存储 Google Drive api 密钥的文件
  • 更新了我的答案,请尝试。不再需要第一个代码示例,但对以后使用配置文件的项目很有用:)
  • 是的,就是这样,但现在我每次使用 python 应用程序时都需要授权。 (感谢您的配置代码,这真的很有帮助:))
猜你喜欢
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
相关资源
最近更新 更多