如何在Flask后端上运行Python脚本?

7
我是一个有用的助手,可以翻译文本。
我有一个小的Flask应用程序,它接受用户输入并返回一些文本。在这里,用户输入被传递给另一个Python脚本temp.py,这个temp.py将返回一个值,应该返回给用户。例如:

flask.py

from flask import Flask, render_template, request
app = Flask(__name__)

@app.route('/')
def result():
    return render_template("index.html")

@app.route('/getconfig', methods=['GET', 'POST'])
def config():
    value = request.form['config']
    print ("This is the user value :  ", value);
    // This value is written to a file say x.pol and my temp.py reads from x.pol file and writes the output to y.pol. I'm not sure how to trigger the script like "python temp.py" on the server.
    // The reason I'm doing this because I don't want to tweak the third party tool where, the third party tool reads from input files and generates output files. 

    return content_generated_by_temp.py // by reading y.pol.

if __name__ == '__main__':
   app.run(debug = True)

顺便提一下,temp.py本身就是一个噩梦。我理解了这个工具的作用。关于该工具的更多信息,请参考:Google Caprica

使用 os 模块调用 temp.py 中的另一个 Python 脚本,或者更好的方法是在 temp.py 中创建一个函数,导入该函数并从 Flask 应用程序中调用。 - Sachin
@SachinKukreja 我无法将其制作为函数。我添加了我正在使用的工具。它有很多依赖项,我不想触碰它们中的任何一个,因为这可能会破坏生成的 pols。 - user5906464
然后,os模块可以完成您的工作。之后,读取由temp生成的输出文件。 - Sachin
1个回答

9

temp.py正在执行的代码封装在一个函数中。将其与flask.py放置在同一目录下。在flask.py中调用import temp,然后使用temp.myfunction()


我肯定会建议使用这个,而不是os。并不是说os不好,但这个更舒服。而且你应该可以使它返回一个对象,而不是写入磁盘然后读取回来。 - Mark

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接