【问题标题】:How to run python script results on Flask如何在 Flask 上运行 python 脚本结果
【发布时间】:2016-08-12 10:33:08
【问题描述】:

我创建了一个 app.py 和 index.html 文件。我的问题是我想在单击提交时使用从 POST 收集的输入执行 python 脚本,然后在相同或不同的 html 页面上显示脚本输出。我使用了 CGI 和 Flask。我不完全知道如何进行。我在网上搜索,但找不到任何有用的东西。任何帮助,将不胜感激。

这是我的代码。

from flask import Flask, render_template, request, redirect

app = Flask(__name__)

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


@app.route("/src_code/main.py", methods = ['POST'])
def run_app():
  id = request.form['id']
  name = request.form['name']
  url = request.form['url']

  if not id or not name or not url:
     return render_template('index.html')
  else:
      #execute the python script.

if __name__ == "__main__":
  app.run()

编辑:

我已使用以下代码导入我的函数。最后,虽然我在点击 index.html 上的提交按钮时收到了错误

   script_analyze = Analyzer()
   result = script_analyze.main()

   return render_template(results.html', data=result)

 AttributeError: 'WSGIRequestHandler' object has no attribute 'environ'

我不确定为什么会引发此属性错误。

【问题讨论】:

  • 我没看出什么问题,你需要的东西都已经有了,在else中用新模板返回即可。
  • 如何使用新模板进行退货?你能给我看个样品吗? @polku
  • 像你之前那样使用return render_template('newtemplate.html', data=script_output),我还是看不出你的问题是什么。
  • 你必须检查它是否是'POST' 语句,然后执行上述操作否则使用return redirect(url_for('abc'))
  • 如果你开始使用烧瓶,我强烈推荐 Miguel Grinbergs Flask Mega Tutorial。真的很好。

标签: python html python-2.7 web flask


【解决方案1】:

既然你想执行另一个 Python 脚本......如果你能够 import 另一个脚本,那么你可以使用类似下面的东西来调用它并存储结果 - 假设另一个脚本是一个值 -返回函数。

from othermodule import function_to_run
...
# where you want to call it
result = function_to_run()

然后您可以像其他人所说的那样使用render_template,将此结果作为数据传递给模板(或者如果结果已经是您想要使用Flask输出的格式,则直接返回结果)。

这行得通吗,或者您要运行的脚本是否行不通?如果有问题,请告诉我们有关脚本的更多信息。

【讨论】:

  • 我已经尝试过你的代码,我设法导入了我的类,它不是一个模块。但是,这次我收到了以下与导入相关的错误。 AttributeError:“WSGIRequestHandler”对象没有属性“环境”@LindsayWard
  • 嗨。您的编辑没有显示您如何imported 任何内容。你也可以包括这个吗?你在任何地方都使用environ吗?
猜你喜欢
  • 2016-09-27
  • 1970-01-01
  • 2016-06-15
  • 1970-01-01
  • 2020-08-07
  • 2017-05-13
  • 2020-01-10
  • 1970-01-01
  • 2022-08-06
相关资源
最近更新 更多