1#!/usr/bin/env python 2 3""" 4Simple Test/Demo Server for running bleach.clean output on various 5desktops. 6 7Usage: 8 9 python server.py 10 11""" 12 13import six 14 15import bleach 16 17 18PORT = 8080 19 20 21class BleachCleanHandler(six.moves.SimpleHTTPServer.SimpleHTTPRequestHandler): 22 def do_POST(self): 23 if six.PY2: 24 content_len = int(self.headers.getheader('content-length', 0)) 25 else: 26 content_len = int(self.headers.get('content-length', 0)) 27 body = self.rfile.read(content_len) 28 print("read %s bytes: %s" % (content_len, body)) 29 30 if six.PY3: 31 body = body.decode('utf-8') 32 print('input: %r' % body) 33 cleaned = bleach.clean(body) 34 35 self.send_response(200) 36 self.send_header('Content-Length', len(cleaned)) 37 self.send_header('Content-Type', 'text/plain;charset=UTF-8') 38 self.end_headers() 39 40 if six.PY3: 41 cleaned = bytes(cleaned, encoding='utf-8') 42 print("cleaned: %r" % cleaned) 43 self.wfile.write(cleaned) 44 45 46if __name__ == '__main__': 47 # Prevent 'cannot bind to address' errors on restart 48 six.moves.socketserver.TCPServer.allow_reuse_address = True 49 50 httpd = six.moves.socketserver.TCPServer(('127.0.0.1', PORT), BleachCleanHandler) 51 print("listening on localhost port %d" % PORT) 52 httpd.serve_forever() 53