Python 是否将API生成的PDF发送到外部服务器?
我有一个NodeJS ExpressJS服务器(用来承载网页)和Django API服务器。当从ExpressJS服务器调用Django服务器中的特定端点时(当用户单击网页上的按钮时),将生成PDF。我想将此PDF从Django服务器发送到ExpressJS服务器,然后将其下载到用户浏览器(用户仅与ExpressJS服务器交互)。为此,我在Django服务器中将PDF编码为base64字符串,并在HTTP响应中返回该字符串。在ExpressJS服务器中,我解码base64字符串,然后使用ExpressJS框架提供的Python 是否将API生成的PDF发送到外部服务器?,python,node.js,django,express,pdf,Python,Node.js,Django,Express,Pdf,我有一个NodeJS ExpressJS服务器(用来承载网页)和Django API服务器。当从ExpressJS服务器调用Django服务器中的特定端点时(当用户单击网页上的按钮时),将生成PDF。我想将此PDF从Django服务器发送到ExpressJS服务器,然后将其下载到用户浏览器(用户仅与ExpressJS服务器交互)。为此,我在Django服务器中将PDF编码为base64字符串,并在HTTP响应中返回该字符串。在ExpressJS服务器中,我解码base64字符串,然后使用Expr
res.download()
方法将PDF下载到用户的浏览器中。此方法似乎有效,但是否会损坏PDF文件?是否有一种方法可以简单地将PDF文件作为二进制文件发送并下载到浏览器(如果可能,请提供一个示例)?非常感谢您的回答、示例和建议
Django API server
def process_upload(request):
'''
Process request and generate PDF
....
'''
with open(pdf, "rb") as pdf_file:
encoded_string = base64.b64encode(pdf_file.read())
return HttpResponse(encoded_string)
ExpressJS server
server.get('/api', function(req, res, next) {
request.post({
url: 'http://<api_url>',
oauth: oauth,
preambleCRLF: true,
postambleCRLF: true
}, function(error, response, body){
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="file.pdf"'
});
});
const download = Buffer.from(body.toString('utf-8'), 'base64');
res.end(download);
});
Django API服务器
def过程_上传(请求):
'''
处理请求并生成PDF
....
'''
打开(pdf,“rb”)作为pdf_文件:
encoded_string=base64.b64encode(pdf_file.read())
返回HttpResponse(编码字符串)
ExpressJS服务器
get('/api',函数(req,res,next){
请寄({
url:'http://',
oauth:oauth,
序言:对,
邮差:对
},函数(错误、响应、正文){
文书标题(200{
“内容类型”:“应用程序/pdf”,
“内容处置”:“附件;文件名=“file.pdf””
});
});
const download=Buffer.from(body.toString('utf-8'),'base64');
res.end(下载);
});
我认为您的代码非常庞大,会将整个
文件.pdf
缓冲到内存中(正文
),在将结果写回客户端之前,如果同时有多个请求,可能会消耗大量内存,这就是为什么您应该使用流:
server.get('/apisd', function(req, res, next) {
// Force browser to download file
res.set('Content-Type', 'application/pdf');
res.set('Content-Disposition', 'attachment; filename=file.pdf');
// send file
request.post({
url: 'http://<api_url>',
oauth: oauth,
preambleCRLF: true,
postambleCRLF: true
}).pipe(res);
});
server.get('/apisd',函数(req、res、next){
//强制浏览器下载文件
res.set('Content-Type','application/pdf');
res.set('Content-Disposition','attachment;filename=file.pdf');
//发送文件
请寄({
url:'http://',
oauth:oauth,
序言:对,
邮差:对
}).管道(res);
});
通过使用streams,程序将一次读取file.pdf
一个块,将其存储到内存中并发送回客户端