Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

this is my Python3 project hiearchy:

projet   \   script.py   web     \     index.html 

From script.py, I would like to run a http server which serve the content of the web folder.

Here is suggested this code to run a simple http server:

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

but this actually serve project, not web. How can I specify the path of the folder I want to serve?

like image 437
roipoussiere Avatar asked Oct 01 '16 00:10

roipoussiere


People also ask

What does python HTTP server do?

Python HTTP server is a kind of web server that is used to access the files over the request. Users can request any data or file over the webserver using request, and the server returns the data or file in the form of a response.


1 Answers

In Python 3.7 SimpleHTTPRequestHandler can take a directory argument:

import http.server import socketserver  PORT = 8000 DIRECTORY = "web"   class Handler(http.server.SimpleHTTPRequestHandler):     def __init__(self, *args, **kwargs):         super().__init__(*args, directory=DIRECTORY, **kwargs)   with socketserver.TCPServer(("", PORT), Handler) as httpd:     print("serving at port", PORT)     httpd.serve_forever() 

and from the command line:

python -m http.server --directory web 

To get a little crazy... you could make handlers for arbitrary directories:

def handler_from(directory):     def _init(self, *args, **kwargs):         return http.server.SimpleHTTPRequestHandler.__init__(self, *args, directory=self.directory, **kwargs)     return type(f'HandlerFrom<{directory}>',                 (http.server.SimpleHTTPRequestHandler,),                 {'__init__': _init, 'directory': directory})   with socketserver.TCPServer(("", PORT), handler_from("web")) as httpd:     print("serving at port", PORT)     httpd.serve_forever() 
like image 155
Andy Hayden Avatar answered Sep 20 '22 10:09

Andy Hayden