需求
flask以及djaogo都属于python Web框架。
由于没有找到flask框架接收文件内容并将文件内容返回的相关方法,只好利用django实现Word转换为PDF的服务。
flask服务将Word docx文件发送给django服务,django将其转换为PDF之后再将PDF文件发送给flask,flask将PDF保存下来
flask:
import requests
from requests_toolbelt import MultipartEncoder
def word2pdf(wordpath):
s = requests
url='django服务地址'
path_pdf = wordpath
print("图片路径:"+path_pdf)
m = MultipartEncoder(
fields={'path': path_pdf,
'file': ('filename', open(wordpath, 'rb'), 'text/plain')
}
)
##将文件内容传输到django服务
r = s.post(url, data=m, headers={'Content-Type': m.content_type})
pdfpath = wordpath.rsplit('.', 1)[0] + '.pdf'
##保存返回的文件内容
with open(pdfpath, 'wb') as pdf:
pdf.write(r.content)
django:
from django.http import HttpResponse
import os
base_dir = 'F:/Project/'
def word2pdf(request):
if request.POST:
global base_dir
wordpath = request.POST.get('path')
wordpath =base_dir + wordpath
print(wordpath)
path = os.path.dirname(wordpath)
if not os.path.isdir(path):
os.makedirs(path)
handle_uploaded_file(request.FILES['file'],wordpath)
##将Word转换为PDF
BASE_DIR = os.path.dirname(__file__) ##project path
print('haha base dir '+BASE_DIR)
cmd = BASE_DIR + 'Docx2PDF.exe ' + wordpath
os.system(cmd)
##将PDF文件传输给flask
pdfpath = wordpath.rsplit('.', 1)[0] + '.pdf'
print('pdf路径:'+pdfpath)
f = open(pdfpath, 'rb')
return HttpResponse(f.read(),content_type='text/plain')
#返回文件时,HttpResponse适合小文件,当文件过大时,可以采用以下方法
#response = StreamingHttpResponse(file_iterator(pdfpath))
#return response
##接收Word文件
def handle_uploaded_file(word,path):
destination = open(path, 'wb+')
for chunk in word.chunks():
destination.write(chunk)
destination.close()