0

为了演示基本的 HTTP 处理,我正在尝试定义一个真正最小的 HTTP 服务器演示。我一直在使用出色的werkzeug库,我正试图将其“哑巴”一点。我当前的服务器做的太多了:)

#!/usr/bin/env python2.7
# encoding: utf-8

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('127.0.0.1', 6969, application=None)

run_simple处理的事情已经太多了。向该服务器发出请求时,

→ http GET http://127.0.0.1:6969/

我们得到:

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/html
Content-Length: 291
Server: Werkzeug/0.8.3 Python/2.7.1
Date: Tue, 08 Jan 2013 07:45:46 GMT

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was 
unable to complete your request.  Either the server 
is overloaded or there is an error in the application.</p>

我很想把它减少到最低限度。并使用 500 Internal Server Error 作为包罗万象的方法。理想情况下,对于任何 HTTP 请求,来自服务器的响应应该是 500,仅此而已,因为服务器对请求一无所知

HTTP/1.0 500 INTERNAL SERVER ERROR

然后在第二阶段,我可能会添加

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/plain

Internal Server Error

然后通过理解请求开始处理请求。目标是在此过程中具有教育意义。欢迎任何关于接管默认答案的建议。

更新 001

和:

#!/usr/bin/env python2.7
# encoding: utf-8

from werkzeug.wrappers import BaseResponse as Response


def application(environ, start_response):
    response = Response('Internal Server Error', status=500)
    return response(environ, start_response)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('127.0.0.1', 6969, application)

它会回来

HTTP/1.0 500 INTERNAL SERVER ERROR
Content-Type: text/plain; charset=utf-8
Content-Length: 21
Server: Werkzeug/0.8.3 Python/2.7.1
Date: Tue, 08 Jan 2013 07:55:10 GMT

Internal Server Error

我想至少删除可选的服务器和日期。

4

1 回答 1

3

作为基本示例,我不会使用第三方库。您可以使用 Python 附带的 BaseHTTPServer 模块。

import BaseHTTPServer

PORT = 8000

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def send_response(self, code, message=None):
        """Send the response header and log the response code.

        In contrast to base class, do not send two standard headers 
        with the server software version and the current date.
        """
        self.log_request(code)
        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
            else:
                message = ''
        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                             (self.protocol_version, code, message))

    def do_GET(self):
        self.send_response(500)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write("Internal Server Error\n")


httpd = BaseHTTPServer.HTTPServer(("", PORT), MyHandler)
print "serving at port", PORT
httpd.serve_forever()

这将给我们以下响应:

HTTP/1.0 500 Internal Server Error
Content-type: text/html

Internal Server Error

您现在可以进行所有更改的地方是 do_GET 方法。我认为每一行的作用很明显。

备选方案 1:

更基本的是

import SocketServer

response = """HTTP/1.0 500 Internal Server Error
Content-type: text/html

Invalid Server Error"""

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """


    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        self.request.sendall(response)

if __name__ == "__main__":
    HOST, PORT = "localhost", 8000
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()
于 2013-01-08T08:29:52.800 回答