1
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()等的調用。我該怎麼做?如何建立一個簡單的HTTP POST服務器?
我不知道你爲什麼要構建這個,但如果它不會收到很多點擊,不需要做任何其他POST和/或GET,並且你不介意公開,你可以使用Google App Engine,易於設置。 – apple16 2012-04-04 22:05:31