Jek*_*son 3 python django google-api google-drive-api google-api-python-client
我需要为我网站的不同用户做一些功能来自动将 html 文件上传到谷歌磁盘并打开它们以在谷歌文档中查看和编辑。为此,我创建了一个文档,将其传递到 google 磁盘并使用创建的文档的 id 在 google docs 中打开它。
为了访问 api,我使用了从服务 Google 帐户中获取的 json 文件。我试图以所有者和查看权限执行我的代码,但结果是一样的。
class CvView(AuthorizedMixin, View):
"""Here I check if the file format is html, I temporarily save it on disk and pass it to the file_to_drive function (to save it to google disk and open it in google docs) and delete it from disk"""
def get(self, request, employee_id, format_):
"""Returns employee's CV in format which is equal to `format_`
parameter."""
employee = get_object_or_404(Employee, pk=employee_id)
user = request.user
content_type, data = Cv(employee, format_, user).get()
if isinstance(data, BytesIO):
return FileResponse(
data, as_attachment=True, filename=f'cv.{format_}',
content_type=content_type)
if content_type == 'text/html':
try:
name = uuid.uuid4().hex + '.html'
with open(name, 'w+') as output:
output.write(str(data))
return HttpResponseRedirect(file_to_drive(import_file=name))
finally:
os.remove(os.path.join(settings.BASE_DIR, name))
return HttpResponse(data, content_type=content_type)
Run Code Online (Sandbox Code Playgroud)
文件到驱动器
from google.oauth2 import service_account
from django.conf import settings
from googleapiclient.discovery import build
SCOPES = [
'https://www.googleapis.com/auth/documents',
'https://www.googleapis.com/auth/drive',
]
ACCOUNT_FILE = os.path.join(settings.BASE_DIR, 'cv-base-gapi.json')
def file_to_drive(import_file=None):
credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': 'My Report',
'mimeType': 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload(import_file,
mimetype='text/html',
resumable=True)
file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: %s' % file.get('id'))
return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
Run Code Online (Sandbox Code Playgroud)
它似乎有效,但有一个不清楚的时刻。
首先,我没有在 Google 磁盘上看到保存的文件,但是该print('File ID: %s' % file.get('id'))行给了我新文档的 id。
第二个最重要的问题是我收到一条关于缺少查看文档的权限的消息。
I could understand about your situation like above. And your question has 2 questions.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
As the main reason of your both questions, I think the use of the service account is the reason. The service account is different from your own Google account. So for example, when the file is created by the service account, the file is created in the Google Drive of the service account. By this, the file cannot be seen at your Google Drive. I think that this is the answer of your question 1. And, the file created in the Google Drive of the service account cannot be directly accessed because only the service account can access to it. I think that this is the answer of your question 2.
In order to see the created Google Document on your Google Drive and make users view and edit the created Google Document, I would like to propose to add the permissions to the created Google Document using Permissions: create in Drive API. When this is reflected to your script, it becomes as follows.
Please modify your script as follows.
From:def file_to_drive(import_file=None):
credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': 'My Report',
'mimeType': 'application/vnd.google-apps.spreadsheet'
}
media = MediaFileUpload(import_file,
mimetype='text/html',
resumable=True)
file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: %s' % file.get('id'))
return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
Run Code Online (Sandbox Code Playgroud)
To:
def file_to_drive(import_file=None):
credentials=service_account.Credentials.from_service_account_file(ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
file_metadata = {
'name': 'My Report',
'mimeType': 'application/vnd.google-apps.document' # Modified
}
media = MediaFileUpload(import_file,
mimetype='text/html',
resumable=True)
file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
fileId = file.get('id') # Added
print('File ID: %s' % fileId)
# --- I added below script.
permission1 = {
'type': 'user',
'role': 'writer',
'emailAddress': '###', # Please set your email of Google account.
}
service.permissions().create(fileId=fileId, body=permission1).execute()
permission2 = {
'type': 'anyone',
'role': 'writer',
}
service.permissions().create(fileId=fileId, body=permission2).execute()
# ---
return (f"https://docs.google.com/document/d/{file.get('id')}/edit")
Run Code Online (Sandbox Code Playgroud)
permission1, your account is added as the writer. By this, you can see the created Document at your Google Drive. Please set your email of Google account here.permission2, in order to make users view and edit the created Document, the permission is added as anyone type. This is a test case. If you want to add the user's emails as the permissions, please set them like permission1.application/vnd.google-apps.spreadsheet to application/vnd.google-apps.document. But in your case, when text/html is converted to application/vnd.google-apps.spreadsheet, it automatically converts to application/vnd.google-apps.document. Because text/html can be converted to only application/vnd.google-apps.document.If I misunderstood your question and this was not the direction you want, I apologize.
| 归档时间: |
|
| 查看次数: |
1965 次 |
| 最近记录: |