| To deliver content with the simple web server set up using http.server, you can place the content (HTML, CSS, JavaScript files, images, etc.) in the same directory where you run the script. The server will serve files from this directory and its subdirectories. Here's an example of how to set up and serve some basic content: Directory Structure: 코드 복사 my_web_server/
├── index.html
├── about.html
├── style.css
└── simple_web_server.py
- HTML Files:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Home</title>
</head>
<body>
<h1>Welcome to My Web Server</h1>
<p>This is the home page.</p>
<a href="about.html">About</a>
</body>
</html>
about.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>About</title>
</head>
<body>
<h1>About This Server</h1>
<p>This is a simple web server created with Python.</p>
<a href="index.html">Home</a>
</body>
</html>
- CSS File:
- Python Server Script:
simple_web_server.py (as given before):
from http.server import SimpleHTTPRequestHandler, HTTPServer
def run_server(port=8000):
server_address = ('', port)
httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
print(f"Starting server on port {port}...")
httpd.serve_forever()
if __name__ == "__main__":
run_server()
Running the Server- Open a terminal or command prompt.
Navigate to the directory where simple_web_server.py is located: cd path/to/my_web_server
Run the server script: python simple_web_server.py
- Open a web browser and go to
http://localhost:8000. You should see the content from index.html.
Accessing Other Pages To access the about.html page, navigate to http://localhost:8000/about.html. The server will automatically serve the appropriate content based on the URL path. This setup allows you to deliver static content (HTML, CSS, JS, images, etc.) from the directory where the server is running. |