# Simple Web Server

This guide demonstrates how to create a custom web server using Python's `http.server` module. Unlike the basic one-liner server, this script can handle dynamic requests (like form submissions) while still serving static files.

**Modules Used:**
*   [[programming/python/modules/http-server-module|http.server]]: To handle HTTP requests.
*   `urllib.parse`: To parse query strings and form data.

## The Code

Save this as `web_server.py`.

```python
import http.server
import socketserver
import urllib.parse

PORT = 8000

class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # Parse query parameters
        parsed_path = urllib.parse.urlparse(self.path)
        query_params = urllib.parse.parse_qs(parsed_path.query)

        # Dynamic Route: /hello
        if parsed_path.path == "/hello":
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            
            name = query_params.get('name', ['World'])[0]
            html = f"<html><body><h1>Hello, {name}!</h1></body></html>"
            self.wfile.write(bytes(html, "utf-8"))
            return

        # Default behavior: Serve static files from current directory
        return http.server.SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        if self.path == "/submit":
            # Get content length
            content_length = int(self.headers['Content-Length'])
            # Read and parse body
            post_data = self.rfile.read(content_length).decode('utf-8')
            form_data = urllib.parse.parse_qs(post_data)

            # Extract data
            user_input = form_data.get('user_input', [''])[0]

            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            
            response = f"""
            <html>
            <body>
                <h2>Form Submitted</h2>
                <p>You entered: <b>{user_input}</b></p>
                <a href="/">Go Back</a>
            </body>
            </html>
            """
            self.wfile.write(bytes(response, "utf-8"))
        else:
            self.send_error(404, "Not Found")

# Create the server
handler_object = MyHttpRequestHandler

print(f"Starting server on port {PORT}...")
print(f"Try: http://localhost:{PORT}/hello?name=Python")

try:
    with socketserver.TCPServer(("", PORT), handler_object) as httpd:
        httpd.serve_forever()
except KeyboardInterrupt:
    print("\nServer stopped.")
```

## Usage

1.  **Run the script:**
    ```bash
    python web_server.py
    ```

2.  **Test Dynamic Route:**
    Open `http://localhost:8000/hello?name=Developer` in your browser.

3.  **Test Form Submission:**
    Create an `index.html` file in the same directory:
    ```html
    <form action="/submit" method="post">
        <label>Enter something:</label>
        <input type="text" name="user_input">
        <input type="submit" value="Send">
    </form>
    ```
    Then open `http://localhost:8000` and submit the form.

[[programming/python/python]]