Python is a powerful scripting language widely used for web development. In many web applications, it is often necessary to display the Python output on an HTML page. In this tutorial, we will learn how to display Python Output on an HTML page. We will primarily use the Flask framework for our example.
Step 1: Setting up the Environment
First, you need to set up an environment suitable for running Python web applications. The simplest way is to use the Python programming language and the Flask framework.
1 |
pip install flask |
Now you are ready to run Flask web applications on your machine.
Step 2: Creating a Python Script
Create a new Python file, let’s call it “app.py”, and put the following code:
1 2 3 4 5 6 7 8 9 10 |
from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello(): text = "Hello, World!" return render_template('index.html', data=text) if __name__ == "__main__": app.run(debug=True) |
In this code, we have created a new Flask web app. The @app.route(“/”) decorator tells Flask to call the function below it whenever someone accesses the root path (“/”) on our website.
Step 3: Creating the HTML Page
Create a new HTML file named “index.html” in the “templates” folder:
1 2 3 4 5 6 |
<!DOCTYPE html> <html> <body> <h1>{{ data }}</h1> </body> </html> |
The index.html file contains an HTML structure with a single h1 tag. Inside this h1 tag, we have used {{ data }}, which is a placeholder for receiving data from our Python script.
Step 4: Running the Application
Now, we can try running our application. Type the following command in the terminal:
1 |
python app.py |
When you visit http://127.0.0.1:5000/ in your web browser, you will see “Hello, World!” which is the output of our Python script.
Here is the full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Python Code from flask import Flask, render_template app = Flask(__name__) @app.route("/") def hello(): text = "Hello, World!" return render_template('index.html', data=text) if __name__ == "__main__": app.run(debug=True) # HTML Code <!DOCTYPE html> <html> <body> <h1>{{ data }}</h1> </body> </html> |
Conclusion
With this, we conclude our tutorial on how to display Python output on an HTML page using Flask. This integration of Python and HTML allows developers to create dynamic web pages powered by Python logic. The same method can be expanded and used to display any data processed via a Python script onto an HTML webpage.