Convert normal Python script to REST API

2024/10/11 16:25:01

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()
Answer

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)
https://en.xdnf.cn/q/118307.html

Related Q&A

How to track changes in specific registry key or file with Python? [closed]

Closed. This question is seeking recommendations for software libraries, tutorials, tools, books, or other off-site resources. It does not meet Stack Overflow guidelines. It is not currently accepting …

How to use Android NDK to compile Numpy as .so?

Because the Numpy isnt a static library(it contains .py files, .pyc files, .so files, etc), so if I want to import it to my python code which is used in an Android phone(using CLE), I should recompile …

passing boolean function to if-condition in python

I"m learning python, and Im trying to do this, which I thought should be trivial, but apparently, its not. $python >>> def isTrue(data): ... "ping" in data ... >>>…

Unsupported operand type(s) for str and str. Python

Ive got the IF statement;if contactstring == "[Practice Address Not Available]" | contactstring == "[]":Im not sure what is going wrong(possibly the " "s?) but I keep ge…

getting Monday , june 5 , 2016 instead of June 5 ,2016 using DateTimeField

I have an app using Django an my my model has the following field: date = models.DateTimeField(auto_now_add=True,auto_now=False)Using that I get this: June 5, 2016, 9:16 p.m.but I need something like…

WeasyPrint usage with Python 3.x on Windows

I cant seem to get WeasyPrint to work on Windows with Python 3.4 or 3.5. Has anyone been able to do this? There arent forums at weasyprint.org and the IRC channel is dead. Ive been able to install …

matplotlib scatter array lengths are not same

i have 2 arrays like this x_test = [[ 14. 1.] [ 14. 2.] [ 14. 3.] [ 14. 4.] [ 14. 5.] [ 14. 6.] [ 14. 7.] [ 14. 8.] [ 14. 9.] [ 14. 10.] [ 14. 11.] [ 14. 12.]]y_test = [ 254.7 255…

APLpy/matplotlib: Coordinate grid alpha levels for EPS quality figure

In the normal matplotlib axes class, it is possible to set gridlines to have a certain transparency (alpha level). Im attempting to utilise this with the APLpy package using the following:fig = pyplot.…

How to extract word frequency from document-term matrix?

I am doing LDA analysis with Python. And I used the following code to create a document-term matrixcorpus = [dictionary.doc2bow(text) for text in texts].Is there any easy ways to count the word frequen…

Remove only overlapping ticks in subplots grid

I have created a subplots grid without any spaces between the subplots, with shared x,y-axes. I only show the ticks and labels for the outer subplots. The problem is that the tick numbers overlap at th…