The main task of the webserver is to handle the HTTP requests from the client. It waits for the HTTP requests coming from the particular IP address and port number, handles the request, and sends the client’s response back. Python uses the SimpleHTTPServer module to create a web server instantly and easily serve the content of the file from the server. It can be used for file sharing also. For this, you have to enable this module with the location of the shareable files. This module comes with the Python interpreter. You don’t need to install it. Since this module is merged with the http.server module in python3, so you have to run http.server to run the webserver in python3. How web server can be used to handle HTTP request and share files, have been shown in this tutorial.
Run the Web Server from the terminal
Run the following command to run the webserver from the terminal. If no port number is defined in the command, the webserver will start at 8000 port by default.
The following output will appear if the webserver is started properly. CTRL+C is pressed to stop the server.
Run the following command to start the webserver at 8080 port.
The following output will appear if the webserver is started at the 8080 port.
Run the Web Server using Python script
Run the following commands to create a folder named web and go to the folder. All the script files and HTML files of this tutorial will be created inside this folder.
$ cd web
Create an HTML file named testHTML.html inside the web folder with the following script. This file will be served from the webserver later.
testHTML.html
<head>
<title>
Test the Python Web Server
</title>
</head>
<body>
<center>
<img src='logo.jpeg' alt='Image not found'/>
<h2 style="color:green">Congratulation! Your Web Server is running Successfully.</h2>
<p>Visit <a href="www.linuxhint.com">LinuxHint.com</a> for more tutorials on Python</p>
</center>
</body>
</html>
Example-1: Run the webserver in the specific port number
Create a python file with the following script to run the webserver at 8008 port. http.server module has been imported to run the webserver, and the SocketServer module has been imported to handle the HTTP request coming from the 8080 port. An object named Handler has been created to handle the HTTP requests. forever() function is called to run the webserver. No termination condition has been added to the script. So, the script will generate an error when the user tries to stop the server.
import http.server
# Import SocketServer module
import socketserver
# Set the port number
port = 8080
# Create object for handling HTTP requests
Handler = http.server.SimpleHTTPRequestHandler
# Run the server forever to handle the HTTP requests
with socketserver.TCPServer(("", port), Handler) as httpd:
print("Web Server is running at http://localhost:%s" %port)
httpd.serve_forever()
Output
The following output will be appeared after executing the above script.
The list of the files and folder of the script location will be shown if the following URL is executed from the browser.
If the user presses CTRL+C from the terminal or presses the stop button from the PyCharm editor, the following error message will be displayed. This problem has solved in the next example of this tutorial.
Example-2: Run the webserver with the port number defined by command-line
Create a python file with the following script to run a web server at the particular port if the command-line argument gives the port number; otherwise, 5000 will be used as the default port. sys module has been imported in the script to read the command-line argument values. try-except block has been added in the script to handle the error when the user tries to stop the server. If the KeyboardInterrupt exception appears after running the server, then the close() function will be called to stop the webserver.
import http.server
# Import SocketServer module
import socketserver
# Import sys module
import sys
try:
# Set the port number
if sys.argv[1:]:
port = int(sys.argv[1])
else:
port = 5000
# Set the IP address
server_address = ('127.0.0.1', port)
# Create object for handling HTTP requests
Handler = http.server.SimpleHTTPRequestHandler
# Run the web server forever to handle the HTTP requests
with socketserver.TCPServer(("", port), Handler) as httpd:
print("Web Server is running at http://localhost:%s" %port)
httpd.serve_forever()
# Stopped the server
except KeyboardInterrupt:
httpd.server_close()
print("The server is stopped.")
Output
The following output will be appeared after executing the above script without command-line argument value.
The following output will appear if the run the HTML file that is created in the previous step from the webserver.
Open the configuration dialog box from the Run menu of the PyCharm editor to set the command-line argument value. Parameters field is used to set the command-line argument, and 3000 is set here as the argument value.
The following output will appear if you run the script again after setting the argument value.
Example-3: Run the webserver with the HTML file
Create a python file with the following script to run the webserver by defining the HTML file for the base URL. The hostname and the port number have defined at the beginning of the script. PythonServer class has defined in the script to display the HTML file in the browser when the web server starts running.
import http.server
# Set the hostname
HOST = "localhost"
# Set the port number
PORT = 4000
# Define class to display the index page of the web server
class PythonServer(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.path = 'testHTML.html'
return http.server.SimpleHTTPRequestHandler.do_GET(self)
# Declare object of the class
webServer = http.server.HTTPServer((HOST, PORT), PythonServer)
# Print the URL of the webserver
print("Server started http://%s:%s" % (HOST, PORT))
try:
# Run the web server
webServer.serve_forever()
except KeyboardInterrupt:
# Stop the web server
webServer.server_close()
print("The server is stopped.")
Output
The following output will appear executing the above script.
The following page will appear in the browser if the browser’s base URL of the webserver executes.
Conclusion
The different ways of implementing web servers by using http. server module has shown in this tutorial to help python users to create a simple web server in Python.