[英]Running a Python code on HTML page using Flask
我是燒瓶的新手。 我想運行我的 Python 項目,當從 HTML 頁面按下開始按鈕並在 HTML 頁面上顯示從 Python 代碼返回的字符串時。 我正在使用 Python 燒瓶。 這是帶有按鈕的 HTML 文件。(HTML 文件的名稱是 json.html)
<!DOCTYPE html>
<html>
<body>
<h1>Smart Job Interviewer</h1>
<button type="button">Start the Interview</button>
</body>
</html>
以下是 Python Flask 文件。 newexecutiontest 是我的 python 文件, run() 是我需要運行的函數。 這個函數返回一個字符串,我想在 HTML 頁面上顯示它。
from flask import Flask
from TextToSpeech import newexecutiontest
from flask import render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('json.html')
def dynamic_page():
return newexecutiontest.run()
if __name__ == '__main__':
app.run(host='0.0.0.0', port='8000', debug=True)
當我運行代碼並加載網頁時,它說“無法訪問此站點”有人可以幫助我完成上述任務。 先感謝您。
您可以將按鈕作為表單的一部分,以便在單擊時將其路由回您的 python 模塊(使用 javascript 可以更輕松地在單擊按鈕時打印字符串,但我假設run()
執行一些邏輯) . 還要向表單添加一些輸入字段,以便您知道它已提交:
<form method="GET">
<input type="hidden" name="start">
<button type="submit">Start the Interview</button>
</form>
現在在燒瓶文件中,您可以執行基本檢查以查看“開始”或您輸入的任何名稱是否存在於 get 請求參數中 - 這意味着表單已提交。 可以將參數傳遞給 html 文件,因此如果表單未提交,我們將傳遞None
或所需的字符串,如果它是:
from flask import request
@app.route('/')
def index():
return render_template('json.html', test_str=dynamic_page() if request.args.get("start") is not None else None)
最后,您可以使用 jinja 模板引擎檢查 html 文件中test_str
的值並相應地打印它。 邏輯在{%
和%}
之間聲明,而評估在{{
和}}
之間聲明。 將此添加到要打印字符串的 html 文件應該可以工作:
{% if test_str is not none %}
<p>{{ test_str }}</p>
{% endif %}
嘗試將 IP 更改為 localhost 或 127.0.0.1
您應該將 html 模板保存在文件夾 /templates 下
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.