How To Send Files Using Python Built-In Http Server
Python’s built-in HTTP server offers a straightforward way to share files over a local network or the internet without the need for complex setups. In this tutorial, we’ll walk through the step-by-step process of using Python’s built-in HTTP server to send files to clients.
Setting Up the HTTP Server
The first step is to start the HTTP server. Open your terminal or command prompt and navigate to the directory containing the files you want to share. Then, execute the following command:
python -m http.server
Accessing Files
Once the server is running, any files in the current directory can be accessed by clients. Clients can use a web browser or an HTTP client to access the files by navigating to the server’s URL followed by the file name.
For example, if the server is running on localhost and port 8000, and there’s a file named example.txt in the directory, it can be accessed at http://localhost:8000/example.txt.
Sending a WebPage Using built-in HTTP Server of Python
Below are step-by-step approaches to send a file in Python using a built-in HTTP server:
Step 1: Create an HTML File
Create an HTML file named index.html with the content you want to display. For example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage!</h1>
<p>This is a sample webpage served using Python's built-in HTTP server.</p>
</body>
</html>
Step 2: Start the HTTP Server
Open your terminal or command prompt, navigate to the directory containing the index.html file, and run the following command:
python -m http.server
This command starts the HTTP server on the default port (8000) and serves files from the current directory.
Step 3: Access the Webpage
Open a web browser and navigate to the following URL:
http://localhost:8000/index.html
You should see the contents of the index.html file displayed in the browser, with the title “My Webpage,” a heading “Welcome to My Webpage!”, and a paragraph with sample text.
Output:
Contact Us