How to customize the page sent by SimpleHTTPServer

2019-09-12 04:25发布

问题:

I am using SimpleHTTPServer class in my code to respond to client requests (it is actually mininet python script for networking project). The client sends a request every 5 seconds to the server 10.0.0.1:

server.cmd('python -m SimpleHTTPServer 80 &')

def tcp_thread(client_id):
    for i in range(180):
        client_id.cmd('wget -O - 10.0.0.1')
        time.sleep(5)

When tracing using Wireshark, I noticed the server sends a junk page of size 390 bytes something like this:

Hypertext Transfer Protocol
    HTTP/1.0 200 OK\r\n
        [Expert Info (Chat/Sequence): HTTP/1.0 200 OK\r\n]
        Request Version: HTTP/1.0
        Status Code: 200
        Response Phrase: OK
    Server: SimpleHTTP/0.6 Python/2.7.6\r\n
    Date: Fri, 08 Jul 2016 16:16:47 GMT\r\n
    Content-type: text/html; charset=UTF-8\r\n
    Content-Length: 390\r\n
    \r\n
    [HTTP response 1/1]
    [Time since request: 0.000905000 seconds]
    [Request in frame: 75]
    File Data: 390 bytes

The page contents looks like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>\n
<title>Directory listing for /</title>\n
<body>\n
<h2>Directory listing for /</h2>\n
<hr>\n
<ul>\n
<li><a href="experiment.py">experiment.py</a>\n
<li><a href="experiment1.mn">experiment1.mn</a>\n
<li><a href="experiment1.py">experiment1.py</a>\n
<li><a href="README">README</a>\n
<li><a href="rules.txt">rules.txt</a>\n
</ul>\n
<hr>\n
</body>\n
</html>\n

My question is: How can I change the page contents so that I can increase the size of the page sent to be larger than 390 bytes? I tried searching about customizing the page and non of them address that clearly.

Thank you.

回答1:

SimpleHTTPServer serves directory listings, files, and index.html, as explained in the documentation: https://docs.python.org/2.7/library/simplehttpserver.html

You can either create index.html file in the same directory, or you can implement the HTTP response yourself by switching to BaseHTTPRequestHandler and overriding do_GET.