我有两个API,一个基本上用于根据发送的数据生成PDF。
下面是第一个 API 端点
http://localhost:5000/api/sendReceiptData
以附件形式返回 PDF 文件。
第二个 API 将使用第一个 API,并应返回 PDF 作为响应中的附件。我已经尝试过,但出现此错误
TypeError: Object of type bytes is not JSON serializable
因此,我如何从第二个 API 中的第一个 API 返回文件响应
您需要使用
send_file
方法返回pdf文件import os
from flask import Flask, make_response, send_file
from werkzeug.utils import secure_filename
app = Flask(__name__)
PDF_FOLDER = '/path/to/pdf/folder' # Replace with the path to your PDF folder
@app.route("/pdf/<string:filename>", methods=['GET'])
def return_pdf(filename):
try:
filename = secure_filename(filename) # Sanitize the filename
file_path = os.path.join(PDF_FOLDER, filename)
if os.path.isfile(file_path):
return send_file(file_path, as_attachment=True)
else:
return make_response(f"File '{filename}' not found.", 404)
except Exception as e:
return make_response(f"Error: {str(e)}", 500