有一个视图构成html文档的正文,并将其提供给网站的新页面(URL-http://localhost/cv/4/html/)
view.py
class CvView(AuthorizedMixin, View):
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)
return HttpResponse(data, content_type=content_type)
urls.py
path('cv/<int:employee_id>/<str:format_>/', CvView.as_view(), name='cv'),
传递给HttpResponse的变量数据包含完整的html文档
<!DOCTYPE html>
<html lang="en">
<head>
.....
</head>
<body>
.....
</body>
我需要将此文档传递到Google驱动器才能打开。为此,我正在使用Google API客户端。创建文档开头的功能如下
def file_to_drive(import_file=None):
SCOPES = 'https://www.googleapis.com/auth/drive'
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.
.....
.....
# GET PERMISSIONS
.....
.....
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
file_metadata = {'name': 'test.html'}
media = MediaFileUpload(import_file, mimetype='text/html')
file = service.files().create(body=file_metadata, media_body=media, fields='id')
response = None
while response is None:
status, response = file.next_chunk()
if status:
print("Uploaded %d%%." % int(status.progress() * 100))
if file:
print(" uploaded successfully")
prem = service.permissions().create(fileId=response.get('id'),
body={'type': 'anyone', 'value': 'anyone', 'role': 'reader', 'withLink': True})
print ("Your sharable link: "+ "https://drive.google.com/file/d/" + response.get('id')+'/view')
return ("https://drive.google.com/file/d/" + response.get('id')+'/view')
然后我在 CvView
的正文中调用此函数class CvView(AuthorizedMixin, View):
"""Employee CV view."""
def get(self, request, employee_id, format_):
...
...
if content_type == 'text/html':
return HttpResponseRedirect(file_to_drive(import_file=data))
file_to_drive(data)
但是仍然有一个重定向到错误的旧网址
OSError: [Errno 36] File name too long: ### include all body of html file
[10/Sep/2019 09:27:48] "GET /cv/4/html/ HTTP/1.1" 500 169860
/home/y700/projects/CV/cv-base/ems/base/google_doc.py changed, reloading.
Exception ignored in: <function MediaFileUpload.__del__ at 0x7f2402a93d90>
Traceback (most recent call last):
File "/home/y700/Env/cv-base-XRtgVf2K/lib/python3.7/site-packages/googleapiclient/http.py", line 567, in __del__
self._fd.close()
AttributeError: 'MediaFileUpload' object has no attribute '_fd'
Watching for file changes with StatReloader
Performing system checks...
如何将html文档正确传输到Google驱动器以便打开?