Serving files

suggest change

Assuming you have the following directory of files:

You can setup a web server to serve these files as follows:

import SimpleHTTPServer
import SocketServer

PORT = 8000

handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("localhost", PORT), handler)
print "Serving files at port {}".format(PORT)
httpd.serve_forever()
import http.server
import socketserver

PORT = 8000

handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), handler)
print("serving at port", PORT)
httpd.serve_forever()

The SocketServer module provides the classes and functionalities to setup a network server.

SocketServer’s TCPServer class sets up a server using the TCP protocol. The constructor accepts a tuple representing the address of the server (i.e. the IP address and port) and the class that handles the server requests.

The SimpleHTTPRequestHandler class of the SimpleHTTPServer module allows the files at the current directory to be served.

Save the script at the same directory and run it.

Run the HTTP Server :

python -m SimpleHTTPServer 8000

python -m http.server 8000

The ‘-m’ flag will search ‘sys.path’ for the corresponding ‘.py’ file to run as a module.

Open localhost:8000 in the browser, it will give you the following:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents