Last active
October 26, 2019 12:01
-
-
Save uneasyguy/7cad89960108f7c8addc6d5643e00ff2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask,jsonify,send_from_directory | |
from flask_restful import Api,Resource,reqparse | |
import werkzeug | |
from PyPDF2 import PdfFileMerger | |
import os | |
app = Flask(__name__) | |
app.config["CLIENT_PDF"] = '/home/****USERNAME GOES HERE****/appscript/' | |
api = Api(app) | |
class Mergy(Resource): | |
def post(self,result_name): | |
base_dir = '/home/****USERNAME GOES HERE****/appscript/' | |
pdf_directory = '/home/****USERNAME GOES HERE****/appsript/pdfs/' | |
parse = reqparse.RequestParser() | |
parse.add_argument('files', type=werkzeug.datastructures.FileStorage, location='files',required=True, action='append') | |
parse.add_argument('Total-Files', location='headers') | |
parse.add_argument('Index', location='headers') | |
args = parse.parse_args() | |
index = args['Index'] | |
total_files = args['Total-Files'] | |
if index<total_files: | |
if index == '1.0': | |
old_pdfs = [f for f in os.listdir(base_dir) if os.path.isfile(os.path.join(base_dir, f)) and f.endswith('.pdf')] | |
if old_pdfs: | |
for x in old_pdfs: | |
os.system(f'rm {x}') | |
try: | |
os.system('rm -r /home/****USERNAME GOES HERE****/appsript/pdfs') | |
os.system('mkdir /home/****USERNAME GOES HERE****/appscript/pdfs') | |
except: | |
os.system('mkdir /home/****USERNAME GOES HERE****/appscript/pdfs') | |
for arg in args['files']: | |
filename = f'{index}.pdf' | |
filepath = f'{pdf_directory}{filename}' | |
arg.save(str(filepath)) | |
return jsonify('success') | |
else: | |
for arg in args['files']: | |
filename = f'{index}.pdf' | |
filepath = f'{pdf_directory}{filename}' | |
arg.save(str(filepath)) | |
pdfs = [f for f in os.listdir(pdf_directory) if os.path.isfile(os.path.join(pdf_directory, f))] | |
pdfs.sort() | |
merger = PdfFileMerger() | |
for pdf in pdfs: | |
filepath = f'{pdf_directory}{pdf}' | |
merger.append(str(filepath)) | |
output = f'{result_name}.pdf' | |
merger.write(output) | |
merger.close() | |
output = output.replace('.pdf','') | |
return jsonify(output) | |
def get(self,result_name): | |
base_dir = '/home/****USERNAME GOES HERE****/appscript/' | |
filename = f'{result_name}.pdf' | |
return send_from_directory(app.config["CLIENT_PDF"], filename=filename, mimetype='application/pdf',as_attachment=True) | |
api.add_resource(Mergy, '/<string:result_name>') | |
app.run(host="0.0.0.0", port=4000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment