Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A Python HTTP server is a simple way to serve web pages using Python. It lets you quickly set up a basic web server on your local machine or network. With a Python HTTP server, you can easily share files, test web applications, or create a temporary hosting environment.
In this article, we will discuss a Python HTTP server and how to set it up with the help of proper examples.
Python SimpleHTTPServer
Python SimpleHTTPServer is a built-in module in Python that allows you to create a simple HTTP server with just a few lines of code. It is part of the Python standard library, which means you don't need to install any additional packages to use it. SimpleHTTPServer is particularly useful for serving static files, such as HTML, CSS, JavaScript, and images.
To start a SimpleHTTPServer, open a command prompt or terminal and navigate to the directory where your files are located. Then, run the following command:
python -m SimpleHTTPServer
By default, SimpleHTTPServer will start serving files on port 8000. You can access the server by opening a web browser and entering `http://localhost:8000` in the address bar. SimpleHTTPServer will display a directory listing of the files in the current folder, and you can click on any file to view or download it.
If you want to use a different port number, you can specify it as an argument when starting SimpleHTTPServer:
python -m SimpleHTTPServer 8080
This will start the server on port 8080 instead of the default 8000.
SimpleHTTPServer is a convenient tool for quickly sharing files or testing simple web pages. However, it is important to note that it is not suitable for production environments or handling complex web applications. You may need to use a more robust web server like Apache or Nginx for more advanced use cases.
Python SimpleHTTPServer Error - No module named SimpleHTTPServer
When trying to start a Python SimpleHTTPServer, you may encounter an error message that says "No module named SimpleHTTPServer". This error occurs when you are using Python 3.x, as the SimpleHTTPServer module has been merged into the `http.server` module in Python 3.
To resolve this error and start a SimpleHTTPServer in Python 3, you need to use the following command instead:
python -m http.server
This command will start the server on the default port 8000. If you want to specify a different port, you can add the port number as an argument:
python -m http.server 8080
For example, let's say you have a website project stored in a directory called "code360" on your local machine. You can navigate to that directory in the command prompt or terminal and run the following command:
python -m http.server
Now, you can open a web browser and enter `http://localhost:8000/code360` to access your website files.
If you are still using Python 2.x, the original command `python -m SimpleHTTPServer` will work as expected.
It's important to note that the SimpleHTTPServer module is deprecated in Python 3 and has been replaced by the `http.server` module. While the functionality remains similar, it's recommended to use the updated module to ensure compatibility with the latest Python versions.
Python SimpleHTTPServer Example
Let's take a closer look at how to use Python SimpleHTTPServer with a practical example. Suppose you have a website project stored in a directory called "code360" on your local machine. The project directory contains HTML, CSS, and JavaScript files.
To serve the website using Python SimpleHTTPServer, follow these steps:
1. Open a command prompt or terminal and navigate to the "code360" directory using the `cd` command:
cd /path/to/code360
2. Once you are inside the "code360" directory, start the SimpleHTTPServer by running the following command:
python -m http.server
This will start the server on the default port 8000.
3. Open a web browser and enter the following URL in the address bar:
http://localhost:8000
This will display the directory listing of the "code360" folder.
4. To access a specific page of your website, append the page's filename to the URL. For example, if you have a file named "index.html" inside the "code360" directory, you can access it by entering:
http://localhost:8000/index.html
SimpleHTTPServer will serve the "index.html" file, and you will see your website rendered in the browser.
5. If you want to access your website from another device on the same network, you can use the IP address of the machine running the SimpleHTTPServer. For example, if your machine's IP address is "192.168.0.10", you can access the website from another device by entering:
http://192.168.0.10:8000
This allows you to test and share your website with others on the same network.
6. To stop the SimpleHTTPServer, press `Ctrl + C` in the command prompt or terminal where the server is running.
Let’s look at an example of how your website's directory structure might look like:
In this example, the "code360" directory contains the main "index.html" file, along with a "style.css" file for styling, a "script.js" file for JavaScript code, and an "images" directory for storing image files.
By running the SimpleHTTPServer in the "code360" directory, you can easily serve and test your website locally before deploying it to a web server like "www.naukri.com/code360".
Python HTTP Server
In addition to the SimpleHTTPServer, Python provides a more flexible and customizable way to create HTTP servers using the `http.server` module. This module allows you to create custom HTTP request handlers and define how the server should respond to different types of requests.
To create a custom HTTP server using the `http.server` module, you need to follow these steps:
Import the necessary modules
from http.server import HTTPServer, SimpleHTTPRequestHandler
Define a custom request handler class that inherits from `SimpleHTTPRequestHandler`
class CustomRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
# Handle GET requests
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Hello, World!')
In this example, we define a `CustomRequestHandler` class that overrides the `do_GET` method to handle GET requests. The method sends a response with a status code of 200, sets the content type to 'text/html', and writes the response body as 'Hello, World!'.
Create an instance of the `HTTPServer` class and specify the server address and the custom request handler
This code creates an instance of the `HTTPServer` class, specifying the server address (an empty string '' means it will listen on all available network interfaces) and the port number (8000 in this case). It also passes the `CustomRequestHandler` class as the request handler.
Start the server
httpd.serve_forever()
This line starts the HTTP server and keeps it running until interrupted.
Now, let's put it all together in a complete example:
from http.server import HTTPServer, SimpleHTTPRequestHandler
class CustomRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = '/index.html'
return SimpleHTTPRequestHandler.do_GET(self)
server_address = ('', 8000)
httpd = HTTPServer(server_address, CustomRequestHandler)
print('Server running on http://localhost:8000')
httpd.serve_forever()
In this example, we create a `CustomRequestHandler` that extends the functionality of `SimpleHTTPRequestHandler`. The `do_GET` method checks if the requested path is the root path ('/') and changes it to '/index.html'. This ensures that when a user visits 'http://localhost:8000', the server serves the 'index.html' file.
We then create an instance of the `HTTPServer` with the server address and the `CustomRequestHandler`. Finally, we start the server and print a message indicating that the server is running on 'http://localhost:8000'.
You can customize the behavior of the server by modifying the `CustomRequestHandler` class and adding more methods to handle different types of requests, such as `do_POST`, `do_PUT`, etc.
Frequently Asked Questions
Can I use Python SimpleHTTPServer for production websites?
No, Python SimpleHTTPServer is not recommended for production environments. It is a lightweight server intended for local development and testing purposes.
How can I set a custom port for Python SimpleHTTPServer?
To set a custom port, you can pass the port number as an argument when starting the server. For example, python -m http.server 8080 will start the server on port 8080.
Is Python SimpleHTTPServer secure?
Python SimpleHTTPServer is not designed with security in mind. It lacks essential security features and should not be used to serve sensitive data or handle production traffic.
Conclusion
In this article, we talked about the Python HTTP servers, especially the built-in SimpleHTTPServer module. We learned how to start a SimpleHTTPServer, serve files, and handle common errors. We also discussed the limitations of SimpleHTTPServer and the need for more advanced web servers in production environments. Additionally, we saw the http.server module and how to create custom HTTP servers with Python.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.