python手动搭建个动态网页不使用python自带的包
要手动搭建一个动态网页,你需要使用Python的标准库socket和http.server来实现一个简单的HTTP服务器。下面是一个示例代码,可以创建一个动态网页,通过HTTP GET请求获取用户输入的数据并在网页上显示出来:
import socket
import sys
def handle_request(request):
request_lines = request.split('\r\n')
request_method, path, protocol = request_lines[0].split(' ')
if request_method == 'GET':
if path == '/':
response_body = """
<html>
<body>
<h1>Dynamic Web Page</h1>
<form method="GET" action="/submit">
<input type="text" name="data" placeholder="Enter your data">
<input type="submit" value="Submit">
</form>
</body>
</html>
"""
elif path.startswith('/submit'):
query_string = path.split('?')[1]
data = query_string.split('=')[1]
response_body = f"""
<html>
<body>
<h1>Submitted Data</h1>
<p>{data}</p>
</body>
</html>
"""
else:
response_body = '<h1>404 Not Found</h1>'
response = f'HTTP/1.1 200 OK\r\nContent-Length: {len(response_body)}\r\n\r\n{response_body}'
return response.encode()
return 'HTTP/1.1 405 Method Not Allowed\r\n\r\n'.encode()
def run_server():
host = ''
port = 8000
try:
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((host, port))
server_socket.listen(1)
print(f'Server is running on http://localhost:{port}')
while True:
client_socket, client_address = server_socket.accept()
request = client_socket.recv(1024).decode()
response = handle_request(request)
client_socket.sendall(response)
client_socket.close()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
run_server()
运行以上代码后,在浏览器中访问http://localhost:8000即可看到一个包含文本输入框的网页。输入数据后点击提交,会在同一页面上显示提交的数据。
请注意,这只是一个简单的示例,仅用于演示目的。在实际开发中,你可能需要使用更高级的框架或库来处理更复杂的动态网页需求
原文地址: https://www.cveoy.top/t/topic/iqiY 著作权归作者所有。请勿转载和采集!