【发布时间】:2020-07-27 18:46:26
【问题描述】:
我在前端使用 React 和 Graphql,在后端使用 Django 和 Graphene。
我希望能够下载报告的 pdf 文件。我尝试使用 mutation 来做到这一点,如下所示:
const [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF)
const handleCreatePDF = async (reportId) => {
const res = await createPdf({variables: {reportId: parseInt(reportId) }})
debugger;
};
export const CREATE_PDF = gql`
mutation ($reportId: Int!) {
createPdf (reportId: $reportId){
reportId
}
}
`;
在后端我有这样的东西:
class CreatePDFFromReport(graphene.Mutation):
report_id = graphene.Int()
class Arguments:
report_id = graphene.Int(required=True)
def mutate(self, info, report_id):
user = info.context.user
if user.is_anonymous:
raise GraphQLError("You are not logged in!")
report = Report.objects.get(id=report_id)
if not report:
raise GraphQLError("Report not found!")
if user != report.posted_by:
raise GraphQLError("You are not permitted to do that!")
html_string = render_to_string('report.html', {'report_id': 1})
pdf_file = HTML(string=html_string)
response = HttpResponse(pdf_file, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="rapport_{}"'.format(report_id)
return response
# return CreatePDFFromReport(report_id=report_id)
当我取消注释 return CreatePDFFromReport(report_id=report_id) 时,它工作正常。
但我想返回 pdf 文件。
有没有可能这样做?
谢谢。
【问题讨论】:
-
@xadm 最好的方法是什么?将其添加为答案,我会接受。
标签: python django reactjs graphql apollo