簡體   English   中英

在Flask中使用html運行python腳本

[英]Running python script using html in 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')

我的process.html如下:

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

和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 %}

我正在使用linux,我不知道是否可以在html中使用exec,如上所示。 但是.html文件中的exec命令沒有執行。 我還是新手,我會建議如何讓它發揮作用。

HTML中的<script>標記專門用於運行客戶端JavaScript代碼。 后端邏輯應該在視圖中完成。 如果您只是想要執行myfile.py存在的一行代碼,您應該將它放在該文件中的函數中並使用from myfile import functionname導入它from myfile import functionname或者只是在視圖中顯示該代碼(后者)在大多數情況下是正確的方法)。 例如,如果myfile.py包含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')

如果您這樣做,則不必將所有代碼拆分為單獨的文件。 不幸的是,模板會在執行代碼后呈現,因此process.html模板中顯示的“Processing ...”會在處理完畢后顯示。 就Flask而言,我知道向用戶顯示進程發生的最佳方式是重定向回頁面並刷新消息,如下所示:

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

然后在home.html你會有這樣的東西(來自Flask 0.11文檔 ):

{% 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 %}

如果您想在頁面上顯示“正在處理...”之類的內容,那就是您希望使用JavaScript的時候。

希望這有助於:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM