我正在设置Django-Heroku应用程序,以允许用户下载视频(最大75MB)。我现在已经尝试了这两种方法,但都没有达到我想要的效果,所以我想知道我是否遇到一些限制或者只是做得不好。
环境
我有一个G Suite帐户,一个具有代理权限的服务帐户。 JSON密钥到位,API已启用,帐户已获得适当范围的授权,我可以下载文件。
我想要的
用户单击链接即可直接从Google云端硬盘下载文件,而无需通过网络应用程序进行传递,登录,病毒警告等操作。它应该是无缝的-单击一次即可下载文件。
class GoogleDrive():
service = 'drive'
version = 'v3'
permissions = ['read'] # Converts to "readonly" scope
connection = connect() # Calls build() with appropriate scope / credentials
尝试1-下载GD文件并以HTTPResponse的身份返回
# Get GD service
gd = GoogleDrive()
request = gd.connection.files().get_media(fileId='<SOME_ID>')
stream = io.BytesIO()
downloader = MediaIoBaseDownload(stream, request)
done = False
# Get file in chunks
for retry in range(0, 5):
while done is False:
status, done = downloader.next_chunk()
# Build response
response = HttpResponse(stream.getvalue(), content_type=<SOME_CONTENT_TYPE>)
response['Content-Disposition'] = 'attachment; filename=sample.mp4' % # force download
response['Content-Length'] = <FILE_SIZE>
return response
从用户的角度来看,这就是我想要的-单击并下载文件。但我觉得文件已处理了两次-一次是将其从Google云端硬盘传输到应用服务器,另一次是将其发送给用户。它可以工作,但是要花一些时间,我觉得它会耗尽Web服务器的资源。
尝试2-将重定向URL返回到GD文件下载
# Get GD service
gd = GoogleDrive()
# Get file content URL
fileinfo = gd.connection.files().get(fileId=<SOME_ID>, fields='webContentLink').execute()
fileurl = fileinfo['webContentLink']
return redirect(fileurl)
这也很接近我想要的,但是,如果我没有登录G Suite帐户,则手机上会出现403错误,或者笔记本电脑上会出现Google登录提示。
是否有一种干净的方法可以使用服务帐户授权来获取我想要的东西?