如何在Flask

时间:2016-08-12 10:33:09

标签: python html python-2.7 web flask

我创建了一个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'

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

1 个答案:

答案 0 :(得分:1)

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

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

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

这是否有效,或者您想要运行的脚本是否适合这种情况?如果这是一个问题,请让我们更多地了解脚本。