Here I have an excel to pdf conversion script. How can I modify it to act as a REST API?
import os
import comtypes.client
SOURCE_DIR = 'D:/projects/python'
TARGET_DIR = 'D:/projects/python'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'ratesheet.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'ratesheet.pdf')
doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()
app.Quit()
You can use Python's Flask lightweight Rest Framework to make your program accessible for REST Calls. Check this tutorial: http://flask.pocoo.org/docs/1.0/tutorial/
There you can simply get the file input in POST format and once the file is converted send a downloadable link to the end user. You have to tweak this code I wrote with a friend for similar purposes:
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filenamePROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDERdef allowed_file(filename):return '.' in filename and \filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS@app.route("/", methods=['GET', 'POST'])
def index():if request.method == 'POST':file = request.files['file']if file and allowed_file(file.filename):filename = secure_filename(file.filename)file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))_path = os.path.abspath("<FILE PATH>")uf = str(uuid.uuid4())# DO YOUR AMAZING STUFF HEREreturn redirect(url_for('index'))return """<!doctype html><title>Upload new File</title><h1>Upload new File</h1><form action="" method=post enctype=multipart/form-data><p><input type=file name=file><input type=submit value=Upload></form><p>%s</p>""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))if __name__ == "__main__":app.run(host='0.0.0.0', port=5001, debug=True)