Last active
August 29, 2015 14:08
-
-
Save js2854/0d04f15001c20f3a2bd6 to your computer and use it in GitHub Desktop.
webserver example do POST and parser xml content of POST data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#-*- coding: UTF-8 -*- | |
import sys | |
import string,cgi,time | |
import xml.etree.ElementTree as ET | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
URL_ROUTE = { | |
'/baidu/' : 'http://baidu.com/', | |
'/google/' : 'http://google.com/' | |
} | |
DEFAULT_URL = 'http://google.com' | |
class MyHandler(BaseHTTPRequestHandler): | |
def _send_response_200(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
def _send_response_302(self): | |
self.send_response(302) | |
location = URL_ROUTE.get(self.path, DEFAULT_URL) | |
self.send_header('Location', location) | |
self.end_headers() | |
self.log_message('Redirect to "%s"'%location) | |
def do_HEAD(self): | |
if self.path == '/': | |
self._send_response_200() | |
else: | |
self._send_response_302() | |
def do_GET(self): | |
'''Respond to a GET request.''' | |
self.do_HEAD() | |
self.wfile.write('<HTML>GET OK.<BR>'); | |
pass | |
def do_POST(self): | |
try: | |
self.do_HEAD() | |
content = self.rfile.read(int(self.headers.getheader('content-length'))) | |
self.wfile.write('<HTML>POST OK.<BR>'); | |
self.log_message('POST data: %s'%content) | |
# <root><person><name>ooo</name></person></root> | |
xml_root = ET.fromstring(content) | |
name = xml_root.find('person/name').text | |
print name | |
except : | |
pass | |
def main(server_address): | |
try: | |
server = HTTPServer(server_address, MyHandler) | |
print 'Serving HTTP on %s port %d ...'%server_address | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print '^C received, Shutting Down HTTP Server' | |
server.socket.close() | |
if __name__ == '__main__': | |
if sys.argv[1:]: | |
port = int(sys.argv[1]) | |
else: | |
port = 8888 | |
server_address = ('127.0.0.1', port) | |
main(server_address) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment