使用Werkzeug的最小HTTP服务器 - 内部服务器错误

时间:2013-01-08 07:51:22

标签: python http werkzeug

为了演示基本的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内部服务器错误作为全部捕获。理想情况下,服务器的响应应该是500,对于任何HTTP请求,只是因为服务器对请求一无所知

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

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

1 个答案:

答案 0 :(得分: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()