I need to do some functionality for different users of my site to automatically upload html files to google disk and open them for viewing and editing in google docs. To do this I create a document, pass it to google disk and use the id of the created document to open it in google docs.
To access api, I use a json file taken from the service Google account. I tried to execute my code with owner and view rights, but the result is the same.
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)
file_to_drive
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")
And it seems to be working, but there's an unclear moment.
First of all, I don't see the saved file on the Google disk, but the print('File ID: %s' % file.get('id'))
line gives me the id of the new document.
And the second most important problem is that I get a message about the missing permissions to view the document.
See Question&Answers more detail:os