2016-08-12 1001 views
-1

我創建了一個app.py和index.html文件。我的問題是,我想用單擊提交時從POST收集的輸入執行python腳本,然後在相同或不同的html頁面上顯示腳本輸出。我使用CGI和Flask。我不完全知道如何繼續。我在網上調查,但找不到任何有用的東西。任何幫助,將不勝感激。如何在Flask上運行python腳本結果

這是我的代碼。

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' 

我不確定爲什麼會引發此屬性錯誤。

+0

我沒有看到問題所在,你已經擁有了所有你需要的東西,只需要使用一個新的模板返回else。 – polku

+0

我如何使用新模板進行退貨?你能給我看一個樣品嗎? @polku – Pythoner1234

+1

像你已經做過的那樣使用'return render_template('newtemplate.html',data = script_output)',我再也看不到你的問題了。 – polku

回答

1

既然你想執行另一個Python腳本......如果你能夠import另一個腳本,那麼你可以使用類似下面的東西來調用它並存儲結果 - 假設其他腳本是一個返回值功能。

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

然後你可以使用render_template如其他人所說的,通過這個結果作爲數據的模板(或簡單地返回的結果,如果它已經在你想輸出與瓶格式)。

這是行不通的,還是腳本你想運行的東西,這不會工作?讓我們更多地瞭解腳本是否有問題。

+0

我試過你的代碼,我設法導入我的類,它不是一個模塊,但是,這次我收到了與導入有關的以下錯誤: AttributeError:'WSGIRequestHandler'對象沒有屬性'environ'@LindsayWard – Pythoner1234

+0

嗨,你的編輯d沒有顯示你如何進口任何東西。你能包括這個嗎? 你是否在任何地方使用'environ'? –