close

How to run a http server which serves a specific path?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to run a http server which serves a specific path in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to run a http server which serves a specific path?

  1. How to run a http server which serves a specific path?

    This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

  2. run a http server which serves a specific path

    This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

Method 1

If you just want serve static file you can do it by running SimpleHTTPServer module using python 2:

 python -m SimpleHTTPServer

Or with python 3:

 python3 -m http.server

This way you do not need to write any script.

Method 2

This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.

So you just need to change the current directory prior to starting the server – see os.chdir

eg:

import http.server
import socketserver
import os

PORT = 8000

web_dir = os.path.join(os.path.dirname(__file__), 'web')
os.chdir(web_dir)

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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read