Running Python Scripts in Web Pages: From Basic Concepts to Practical Implementation

Nov 21, 2025 · Programming · 9 views · 7.8

Keywords: Python Web Execution | CGI Protocol | Flask Framework | Web Server | WSGI Interface

Abstract: This article provides an in-depth exploration of the core principles and technical implementations for executing Python scripts in web environments. By analyzing common misconceptions, it systematically introduces the role of web servers, the working mechanism of CGI protocol, and the application of modern Python web frameworks. The article offers detailed explanations of the entire process from simple CGI scripts to complete Flask application development, accompanied by comprehensive code examples and configuration instructions to help developers understand the essence of server-side script execution.

Understanding the Basic Principles of Python Script Execution in Web Pages

Many Python beginners encounter a common issue when attempting to deploy locally developed scripts to web environments: browsers display the source code directly instead of execution results. The fundamental cause of this phenomenon lies in the lack of understanding of web working principles. When users access http://localhost/index.py through a browser, if no appropriate web server is configured in the system, the browser is actually reading and displaying file content directly, rather than executing the script through a server.

The Critical Role of Web Servers

In standard web architecture, servers play a core middleware role. When a browser sends an HTTP request, the server first receives the request, then determines how to process it based on the requested URL. For Python script files, the server needs to have appropriate interpreters to execute the code and return the execution results to the browser, rather than simply transmitting file content.

Common web servers include Apache, Nginx, etc. These servers can support Python script execution through module extensions. For example, Apache server can handle Python requests through the mod_wsgi module or traditional CGI (Common Gateway Interface) approach.

CGI: Traditional Server-Side Script Execution Solution

CGI is one of the earliest standards for server-side script execution, providing a standard interface protocol between web servers and external programs. To run Python scripts using CGI approach, the following configuration is required:

First, the script file needs to be renamed with .cgi extension, and necessary header information needs to be added at the beginning of the file:

#!/usr/bin/python
print("Content-type: text/html\r\n\r\n")
print("Hi Welcome to Python test page<br>")
print("Now it will show a calculation<br>")
print("30+2=")
print(30+2)

In Linux systems, execution permissions also need to be added to the script file: chmod +x index.cgi. The first line shebang (#!/usr/bin/python) specifies the interpreter path for executing the script, while the Content-type header tells the browser the format of the returned content.

Advantages of Modern Python Web Frameworks

Although the CGI solution is simple and easy to use, modern Python web frameworks provide more powerful and efficient options in actual production environments. Flask, as a lightweight framework, is particularly suitable for beginners and small projects:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    result = ""
    result += "Hi Welcome to Python test page<br>"
    result += "Now it will show a calculation<br>"
    result += "30+2=" + str(30+2)
    return result

if __name__ == '__main__':
    app.run(debug=True)

Flask maps URL paths to specific Python functions through route decorators (@app.route('/')). When users access the corresponding path, the associated function is automatically called, and its return value is sent back to the browser as an HTTP response.

Server Configuration and Deployment Practice

Server configuration is a key环节 in implementing complete Python web applications. Taking Apache server as an example, configuring CGI support requires enabling relevant modules in the httpd.conf file:

LoadModule cgi_module modules/mod_cgi.so
<Directory "/path/to/your/cgi-bin">
    Options +ExecCGI
    AddHandler cgi-script .cgi .py
</Directory>

For Flask applications, WSGI (Web Server Gateway Interface) can be used for deployment, which is the standard interface between Python web applications and web servers. Through the mod_wsgi module, Flask applications can be integrated into Apache server:

# flask_app.wsgi
import sys
sys.path.insert(0, '/path/to/your/application')
from yourapplication import app as application

Practical Application Scenarios and Best Practices

In the fields of IoT and embedded systems, Python web applications have widespread applications. For example, controlling GPIO (General Purpose Input/Output) devices through web pages:

from flask import Flask, render_template, request
import RPi.GPIO as GPIO

app = Flask(__name__)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

@app.route('/')
def index():
    return render_template('control.html')

@app.route('/control', methods=['POST'])
def control():
    action = request.form['action']
    if action == 'on':
        GPIO.output(18, GPIO.HIGH)
        return "Device turned ON"
    else:
        GPIO.output(18, GPIO.LOW)
        return "Device turned OFF"

This architecture allows users to remotely control physical devices through web interfaces, demonstrating Python's powerful capabilities in combining web development with hardware control.

Security Considerations and Performance Optimization

When deploying Python web applications, security is an important factor that cannot be ignored. For CGI solutions, attention needs to be paid to input validation and permission control to avoid security risks such as command injection. For frameworks like Flask, built-in security features such as template auto-escaping and session management can be utilized.

In terms of performance, CGI incurs significant overhead since each request requires starting a new Python process, making it suitable for low-concurrency scenarios. The WSGI solution, by reusing Python interpreters through process pools or thread pools, can significantly improve concurrent processing capabilities.

By understanding these core concepts and technical implementations, developers can better deploy and run Python scripts in web environments. From simple page output to complex web application development, Python provides complete and powerful solutions.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.