Reputation: 145
I am new to Flask. I want to run my Python project, when the start button is pressed from the HTML page and display the string which is returned from the Python code, on the HTML page. I am using Python flask. This is the HTML file with the button.(The name of the HTML file is json.html)
<!DOCTYPE html>
<html>
<body>
<h1>Smart Job Interviewer</h1>
<button type="button">Start the Interview</button>
</body>
</html>
Following is the Python flask file. newexecutiontest is my python file and run() is the function that I need to run. This function returns a string and I want to display it on the HTML page.
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)
When I run the code and load the web page it says that "This site can't be reached" Can someone please help me to achieve the above task. Thank you in advance.
Upvotes: 0
Views: 1981
Reputation: 26
Try changing the IP to localhost or 127.0.0.1
You should keep the html template under the folder /templates
Upvotes: 1
Reputation: 1447
You could make the button part of a form, so that it is routed back to your python module on click (just printing a string on button click could more easily be done with javascript, but I assume run()
performs some logic as well). Also add some input field to the form so you can know it was submitted:
<form method="GET">
<input type="hidden" name="start">
<button type="submit">Start the Interview</button>
</form>
Now in the flask file, you can perform a basic check to see if "start", or whatever name you gave your input, exists in the get request arguments - which would mean the form was submitted. It is possible to pass arguments to an html file, so we will pass None
if the form wasn't submitted or the desired string if it was:
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)
And finally, you can check the value of test_str
in the html file and print it accordingly, using the jinja templating engine. Logic is declared between {%
and %}
, while evaluations are declared between {{
and }}
. Adding this to the html file where you want the string to be printed should work:
{% if test_str is not none %}
<p>{{ test_str }}</p>
{% endif %}
Upvotes: 1