将普通的Python脚本转换为REST API [英] Convert normal Python script to REST API

查看:49
本文介绍了将普通的Python脚本转换为REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我有一个Excel到pdf转换脚本.如何修改它以充当REST API?

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

推荐答案

您可以使用Python的Flask轻量级Rest Framework来使您的程序可用于REST调用.检查此教程: http://flask.pocoo.org/docs/1.0/tutorial/

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/

您可以在其中简单地获取POST格式的文件输入,并且在文件转换后,将可下载的链接发送给最终用户.您必须调整我与朋友写的这段代码,用于类似目的:

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_filename



PROJECT_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_FOLDER

def 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 HERE
            return 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)

这篇关于将普通的Python脚本转换为REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆