Python has a simple HTTP server function for web development. It's convenient, but it's inconvenient because I have to put the public script directly under the directory I want to publish (I thought), and I just found out how to specify the public directory.
(Supports Python 3.7 and above) Below, you can enter the relative path from the script in __DIRECTORY.
Quoted from Reference 1
server.py
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()
StackOverflow "How to run a http server which serves a specific path?" I just wrote what I wanted to know.
If you do not specify a public directory, you can use the following code. The directory where the script exists automatically becomes the public directory. By passing a handler to TCPServer () as an argument, the appropriate argument is put in the constructor of SimpleHTTPRequestHandler in TCPServer (). So this __Handler is an image like a function pointer __. (That is, is it a "handler"?)
Do not specify a directory.py
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
So, what we are doing in the code of the above conclusion is to call the constructor of SimpleHTTPRequestHandler in TCPServer () without changing the outline (* args and ** kwargs in the code below), The __constructor is overwritten so that "arbitrary specified directory" is passed to the argument directory.
I investigated only the difficult parts.py
#Redefine the initialization function of SimpleHTTPRequestHandler
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
#I really want to do this, but I get an error with insufficient arguments.
#The argument is TCP Server()I can't put it in here & I don't know because I put it properly inside.
Handler = http.server.SimpleHTTPRequestHandler(directory="web")
#This is no good either. Naturally, it is said what args are.
Handler = http.server.SimpleHTTPRequestHandler(*args,directory="web",**kwargs)
From python specifications http.server
so! All I want to do is put the arguments in the following directories!
Let's init a derived class using inheritance and super () in python I didn't understand the part of overwriting the constructor, so I was taken care of. How to use Python variable length arguments (* args, ** kwargs)
Recommended Posts