From Static to Dynamic: Delivering Dynamic 🖥️ Content on Web Pages 📃 using Python 🐍

Pramod Kumar Gupta
2 min readJul 23, 2023

--

“What is a Dynamic Web Page?
A dynamic web page is one that presents varying content to different users while maintaining a consistent layout and design. These pages are typically created using technologies such as CGI, AJAX, ASP, or ASP.NET and may take slightly longer to load compared to simple static pages. They are commonly employed to display information that changes frequently, such as weather updates or stock prices.

How are Dynamic Web Pages Processed?
The processing of dynamic web pages differs from static pages. When a user requests a dynamic page from the web server, it doesn’t directly send the complete page to the browser as it would with a static page. Instead, the web server passes the page to the application server, which undertakes three main activities:
1. Reading the code embedded in the page.
2. Rendering the page based on the instructions within the code.
3. Stripping away the code, leaving behind the final content for the user.

To build a Dynamic Web Page, follow the steps below:”

Install httpd

yum install httpd

Upon installation, this module generates two directories: “/var/www/html” to store HTML files and “/var/www/cgi-bin” to house Python scripts.

Now go /var/www/html and create a index.html file and write the given code below .

<script>
function run() {
var cmd = document.getElementById('inp').value;
var xhr = new XMLHttpRequest();
xhr.open('GET','http://IP/cgi-bin/cmd.py?cmd='+cmd);
xhr.send();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
document.getElementById('outp').innerHTML = this.responseText;
}
}
}
</script>

<center>
<h1>Welcome to UR Company</h1>
root@ip-15-206-117-66]# <input id='inp' name='cmd'/><br><br>
<button onclick="run()">Run</button><br><br>
<div id='outp'>Data is coming</div>
</center>

Now got /var/www/cgi-bin folder and create a file name cmd.py. Make it executable and write the following code .

#!/usr/bin/python3

import subprocess
import cgi

print("content-type: text/html")
print()

form = cgi.FieldStorage()
cmd = form.getvalue("cmd")
output = subprocess.getoutput(cmd)
print("<pre>" + output + "</pre>")

For making the file executable use the following ..

chmod +x filename

Now open the web page using the format -

http://IP:Port/index.html

Dynamic Content retrieval from cmd.py to index.html page.

Thanks for reading….

--

--