好吧,现在我的django应用程序中有一个函数可以创建一个word文档,如下所示:
ngOnInit() {
this.myService.getOptions().subscribe(data => this.options = data.carriers);
this.selectedOption.valueChanges.pipe(
startWith<string | Option>(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this.filterByName(name) : this.options.slice()),
tap(filtered => {
// If ever this evelauates to true, the panel stops appearining
// and when it evaluates back to false
// it is as if all of auto-complete stops working.
this.callAMethod(filtered);
}
).subscribe(filtered => this.filteredOptions = filtered);
}
callAMethod(filtered) {
this.disablePanel = filtered.length > 6;
}
现在,该文件被用作def form_view(request):
if request.method == 'POST':
#do a bunch of things
context = {
'model_1' : model_1,
}
in_template = "Forms/mytemplate.docx"
doc = DocxTemplate(in_template)
doc.render(context)
out_filename = "outfile.docx"
http_word_response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
http_word_response['Content-Disposition'] = 'attachment; filename=%s' % out_filename
doc.save(http_word_response)
return http_word_response
else:
return render( request, 'mysite/form.html', context)
变量,并且效果很好
我想更改此设置,以便实际上创建文件并将其保存到S3中,但是我不想先在本地保存文件,而只是使用python-docx包的流函数:https://python-docx.readthedocs.io/en/latest/user/documents.html#opening-a-file-like-document
这是它提供的示例:
http_word_response
我不确定如何将该样本转换为我的模板文件中的内容,然后输出一个文件/对象,然后将其发送到S3并执行某些操作。
我的最佳猜测是这样的:
with open('foobar.docx', 'rb') as f:
source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
...
target_stream = StringIO()
document.save(target_stream)
但是随后,我对 with open(in_template, 'rb') as f:
source_stream = StringIO(f.read())
doc = DocxTemplate(source_stream)
source_stream.close()
target_stream = StringIO()
document.save(target_stream)
部分的去向以及如何将doc.render(context)
的名称更改为所需的文件名感到困惑。
感谢您提供有关入门的任何帮助。