如何构建一个简单的HTTP POST服务器?

时间:2012-04-04 19:21:15

标签: python http

class MyHandler( BaseHTTPServer.BaseHTTPRequestHandler):
    def do_POST( self ):
        ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
        postvars = {}
        try:
          if ctype == 'application/x-www-form-urlencoded':
              length = int(self.headers.getheader('content-length'))
              postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)

          self.send_response( 200 )
          self.send_header( "Content-type", "text")
          self.send_header( "Content-length", str(len(body)) )
          self.end_headers()
          self.wfile.write(body)
        except:
          print "Error"


def httpd(handler_class=MyHandler, server_address = ('2.3.4.5', 80)):
    try:
        print "Server started"
        srvr = BaseHTTPServer.HTTPServer(server_address, handler_class)
        srvr.serve_forever() # serve_forever
    except KeyboardInterrupt:
        server.socket.close()


if __name__ == "__main__":
    httpd( )

我已准备好大部分代码。如果客户端处于非活动状态或者没有响应10秒(类似https://stackoverflow.com/a/265741/204623),我需要添加用于关闭连接的代码。基本上我不希望服务器在调用send_response(),wfile.write()等时不阻塞。我该怎么做?

1 个答案:

答案 0 :(得分:3)

试试这个:

import BaseHTTPServer

class TimeoutServer(BaseHTTPServer.HTTPServer):
    def get_request(self):
        result = self.socket.accept()
        result[0].settimeout(10)
        return result

然后使用TimeoutServer类代替HTTPServer来获得超时支持。