在Flask中使用html运行python脚本

Ann*_*Ann 4 html python flask

我是Flask的新手,并且我试图在HTML页面中单击按钮时从后台运行python脚本。这是我的代码:

    app.py
    from flask import *
    from functools import wraps
    import sqlite3

    app = Flask(__name__)
    @app.route('/')
    def home():
       return render_template('home.html')

    @app.route('/generate')
    def generate():
       return render_template('process.html')
Run Code Online (Sandbox Code Playgroud)

我的process.html如下:

   <html>
   <head>
   <body>
        Processing...
   <script>
        exec('python /pth to my python file/myfile.py')
  </script>
  </body>
  </head></html>
Run Code Online (Sandbox Code Playgroud)

和home.html如下:

  {% extends "template.html" %}
  {% block content %}
  <div class = "jumbo">
  <h2> Home</h2>
  <br/>
  <p><a href="{{ url_for('generate') }}">click me</a></p>
  <p> lorem epsum </p>
  <div>
  {% endblock %}
Run Code Online (Sandbox Code Playgroud)

我正在Linux上工作,不知道是否可以在html中使用exec,如上所示。但是.html文件中的exec命令未执行。我仍然对Flask还是陌生的,并且我会就如何使其工作提出任何建议。

Tae*_*ott 5

<script>HTML中的标记专门用于运行客户端JavaScript代码。后端逻辑应在视图中完成。如果您只是想执行中存在的代码行myfile.py,则应将其放在该文件中的函数中,然后使用from myfile import functionname或简单地将这些代码存在于视图中进行导入(后者是正确的做法)绝大多数情况下)。例如,如果myfile.py包含,print 'Hello World!'则您的视图应如下所示:

from flask import *
from functools import wraps
import sqlite3

app = Flask(__name__)
@app.route('/')
def home():
   return render_template('home.html')

@app.route('/generate')
def generate():
   print 'Hello World!'
   return render_template('process.html')
Run Code Online (Sandbox Code Playgroud)

如果以这种方式进行操作,则无需将所有代码拆分为单独的文件。但是不幸的是,模板将在执行代码后呈现,因此process.html模板中显示的“正在处理...”将在处理完之后显示。就Flask而言,我所知道的向用户显示该过程已发生的最好方法是重定向回页面并闪烁一条消息,如下所示:

@app.route('/generate')
def generate():
   print 'Hello World!'
   flash('Process complete!')
   return redirect(url_for(home))
Run Code Online (Sandbox Code Playgroud)

然后home.html您会有类似这样的内容(来自Flask 0.11 Documentation):

{% extends "template.html" %}
{% block content %}
<div class = "jumbo">
<h2> Home</h2>
<br/>
{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
      {% for message in messages %}
        <li>{{ message }}</li>
      {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
<p><a href="{{ url_for('generate') }}">click me</a></p>
<p> lorem epsum </p>
<div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

如果您希望在页面上显示“正在处理...”之类的信息,那就是您要使用JavaScript的时候。

希望这会有所帮助:)