annotate python/pythonServer.py @ 2450:c602b4c69310

Hotfix: Pseudo failure in pythonServer for 3.x
author Nicholas Jillings <nicholas.jillings@mail.bcu.ac.uk>
date Tue, 02 Aug 2016 10:35:43 +0100
parents aca96a5183be
children 8536e978ab6f
rev   line source
b@2264 1 #!/usr/bin/python
b@2264 2
b@2264 3 # Detect the Python version to switch code between 2.x and 3.x
b@2264 4 # http://stackoverflow.com/questions/9079036/detect-python-version-at-runtime
b@2264 5 import sys
b@2264 6
b@2264 7 import inspect
b@2264 8 import os
b@2264 9 import pickle
b@2264 10 import datetime
nicholas@2430 11 import operator
nicholas@2430 12 import xml.etree.ElementTree as ET
nicholas@2431 13 import copy
b@2264 14
b@2264 15 if sys.version_info[0] == 2:
b@2264 16 # Version 2.x
b@2264 17 import BaseHTTPServer
b@2264 18 import urllib2
b@2264 19 import urlparse
b@2264 20 elif sys.version_info[0] == 3:
b@2264 21 # Version 3.x
b@2264 22 from http.server import BaseHTTPRequestHandler, HTTPServer
b@2264 23 import urllib as urllib2
b@2264 24
b@2264 25 # Go to right folder.
b@2264 26 scriptdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
b@2264 27 os.chdir(scriptdir) # does this work?
b@2264 28
b@2264 29 PSEUDO_PATH = '../tests/'
b@2264 30 pseudo_files = []
nicholas@2450 31 pseudo_index = 0
nicholas@2430 32 for filename in os.listdir(PSEUDO_PATH):
b@2264 33 print(filename)
b@2264 34 if filename.endswith('.xml'):
b@2264 35 pseudo_files.append(filename)
b@2264 36
b@2264 37 curSaveIndex = 0;
b@2264 38 curFileName = 'test-0.xml'
nicholas@2430 39 while(os.path.isfile('../saves/'+curFileName)):
b@2264 40 curSaveIndex += 1;
b@2264 41 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 42
b@2264 43 if len(pseudo_files) > 0:
b@2264 44 pseudo_index = curSaveIndex % len(pseudo_files)
b@2264 45 else:
b@2264 46 pseudo_index = 0
b@2264 47
b@2264 48 print('URL: http://localhost:8000/index.html')
b@2264 49
b@2264 50 def send404(s):
b@2264 51 s.send_response(404)
b@2264 52 s.send_header("Content-type", "text/html")
b@2264 53 s.end_headers()
b@2264 54
b@2264 55 def processFile(s):
b@2264 56 if sys.version_info[0] == 2:
b@2264 57 s.path = s.path.rsplit('?')
b@2264 58 s.path = s.path[0]
b@2264 59 s.path = s.path[1:len(s.path)]
b@2264 60 st = s.path.rsplit(',')
b@2264 61 lenSt = len(st)
b@2264 62 fmt = st[lenSt-1].rsplit('.')
b@2264 63 fpath = "../"+urllib2.unquote(s.path)
n@2432 64 size = os.path.getsize(fpath)
b@2264 65 fileDump = open(fpath)
b@2264 66 s.send_response(200)
b@2264 67
b@2264 68 if (fmt[1] == 'html'):
b@2264 69 s.send_header("Content-type", 'text/html')
b@2264 70 elif (fmt[1] == 'css'):
b@2264 71 s.send_header("Content-type", 'text/css')
b@2264 72 elif (fmt[1] == 'js'):
b@2264 73 s.send_header("Content-type", 'application/javascript')
b@2264 74 else:
b@2264 75 s.send_header("Content-type", 'application/octet-stream')
b@2264 76 s.send_header("Content-Length", size)
b@2264 77 s.end_headers()
b@2264 78 s.wfile.write(fileDump.read())
b@2264 79 fileDump.close()
b@2264 80 elif sys.version_info[0] == 3:
b@2264 81 s.path = s.path.rsplit('?')
b@2264 82 s.path = s.path[0]
b@2264 83 s.path = s.path[1:len(s.path)]
b@2264 84 st = s.path.rsplit(',')
b@2264 85 lenSt = len(st)
b@2264 86 fmt = st[lenSt-1].rsplit('.')
b@2264 87 fpath = "../"+urllib2.parse.unquote(s.path)
b@2264 88 s.send_response(200)
b@2264 89 if (fmt[1] == 'html'):
b@2264 90 s.send_header("Content-type", 'text/html')
b@2264 91 fileDump = open(fpath, encoding='utf-8')
b@2264 92 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 93 fileDump.close()
b@2264 94 elif (fmt[1] == 'css'):
b@2264 95 s.send_header("Content-type", 'text/css')
b@2264 96 fileDump = open(fpath, encoding='utf-8')
b@2264 97 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 98 fileDump.close()
b@2264 99 elif (fmt[1] == 'js'):
b@2264 100 s.send_header("Content-type", 'application/javascript')
b@2264 101 fileDump = open(fpath, encoding='utf-8')
b@2264 102 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 103 fileDump.close()
b@2264 104 else:
b@2264 105 s.send_header("Content-type", 'application/octet-stream')
b@2264 106 fileDump = open(fpath, 'rb')
b@2264 107 fileBytes = fileDump.read()
b@2264 108 fileDump.close()
b@2264 109 s.send_header("Content-Length", len(fileBytes))
b@2264 110 s.end_headers()
b@2264 111 s.wfile.write(fileBytes)
b@2264 112
b@2264 113 def keygen(s):
b@2264 114 reply = ""
b@2264 115 options = s.path.rsplit('?')
b@2264 116 options = options[1].rsplit('=')
b@2264 117 key = options[1]
b@2264 118 print("Registered key "+key)
b@2264 119 if os.path.isfile("saves/save-"+key+".xml"):
b@2264 120 reply = "<response><state>NO</state><key>"+key+"</key></response>"
b@2264 121 else:
b@2264 122 reply = "<response><state>OK</state><key>"+key+"</key></response>"
b@2264 123 s.send_response(200)
b@2264 124 s.send_header("Content-type", "application/xml")
b@2264 125 s.end_headers()
nicholas@2377 126 if sys.version_info[0] == 2:
nicholas@2377 127 s.wfile.write(reply)
nicholas@2377 128 elif sys.version_info[0] == 3:
nicholas@2377 129 s.wfile.write(bytes(reply, "utf-8"))
b@2264 130 file = open("../saves/save-"+key+".xml",'w')
b@2264 131 file.write("<waetresult key="+key+"/>")
b@2264 132 file.close();
b@2264 133
b@2264 134 def saveFile(self):
b@2264 135 global curFileName
b@2264 136 global curSaveIndex
b@2264 137 options = self.path.rsplit('?')
b@2264 138 options = options[1].rsplit('=')
b@2264 139 key = options[1]
b@2264 140 varLen = int(self.headers['Content-Length'])
b@2264 141 postVars = self.rfile.read(varLen)
b@2264 142 print("Saving file key "+key)
nicholas@2376 143 file = open('../saves/save-'+key+'.xml','wb')
b@2264 144 file.write(postVars)
b@2264 145 file.close()
b@2264 146 try:
b@2264 147 wbytes = os.path.getsize('../saves/save-'+key+'.xml')
b@2264 148 except OSError:
b@2264 149 self.send_response(200)
b@2264 150 self.send_header("Content-type", "text/xml")
b@2264 151 self.end_headers()
b@2264 152 self.wfile.write('<response state="error"><message>Could not open file</message></response>')
b@2264 153 self.send_response(200)
b@2264 154 self.send_header("Content-type", "text/xml")
b@2264 155 self.end_headers()
nicholas@2376 156 reply = '<response state="OK"><message>OK</message><file bytes="'+str(wbytes)+'">"saves/'+curFileName+'"</file></response>'
nicholas@2382 157 if sys.version_info[0] == 2:
nicholas@2382 158 self.wfile.write(reply)
nicholas@2382 159 elif sys.version_info[0] == 3:
nicholas@2382 160 self.wfile.write(bytes(reply, "utf-8"))
b@2264 161 curSaveIndex += 1
b@2264 162 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 163
nicholas@2430 164 def poolXML(s):
nicholas@2430 165 pool = ET.parse('../tests/pool.xml')
nicholas@2430 166 root = pool.getroot()
nicholas@2430 167 setupNode = root.find("setup");
nicholas@2430 168 poolSize = setupNode.get("poolSize",0);
nicholas@2430 169 if (poolSize == 0):
nicholas@2430 170 s.path = s.path.split("/php",1)[0]+"/tests/pool/xml"
nicholas@2430 171 processFile(s)
nicholas@2430 172 return
nicholas@2431 173 poolSize = int(poolSize)
nicholas@2430 174 # Set up the store will all the test page key nodes
nicholas@2430 175 pages = {};
nicholas@2430 176 for page in root.iter("page"):
nicholas@2430 177 id = page.get("id")
nicholas@2430 178 pages[id] = 0
nicholas@2430 179 # Read the saves and determine the completed pages
nicholas@2430 180 for filename in os.listdir("../saves/"):
nicholas@2430 181 if filename.endswith(".xml"):
nicholas@2430 182 save = ET.parse("../saves/"+filename)
nicholas@2430 183 save_root = save.getroot();
nicholas@2431 184 if (save_root.find("waet").get("url") == "http://localhost:8000/php/pool.php"):
nicholas@2431 185 for page in save_root.findall("./page"):
nicholas@2431 186 id = page.get("ref")
nicholas@2430 187 pages[id] = pages[id] + 1
nicholas@2430 188
nicholas@2430 189 # Sort the dictionary
nicholas@2431 190 rot_pages = {}
nicholas@2431 191 for key, value in pages.items():
nicholas@2431 192 if (value in rot_pages):
nicholas@2431 193 rot_pages[value].append(key)
nicholas@2431 194 else:
nicholas@2431 195 rot_pages[value] = [key]
nicholas@2431 196
nicholas@2431 197 Keys = list(rot_pages)
nicholas@2431 198 print ("Current pool state:")
nicholas@2431 199 print (rot_pages)
nicholas@2431 200
nicholas@2431 201 return_node = ET.fromstring('<waet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="test-schema.xsd"/>');
nicholas@2431 202 return_node.append(copy.deepcopy(root.find("setup")))
nicholas@2431 203 page_elements = root.findall("page")
nicholas@2430 204
nicholas@2431 205 # Now append the pages
nicholas@2431 206 i = 0
nicholas@2431 207 while(len(return_node.findall("page")) < poolSize):
nicholas@2431 208 if (i > 0):
nicholas@2431 209 for page in return_node.iter("page"):
nicholas@2431 210 page.set("alwaysInclude","true")
nicholas@2431 211 for id in rot_pages[Keys[i]]:
nicholas@2431 212 return_node.append(copy.deepcopy(root.find('./page[@id="'+id+'"]')))
nicholas@2431 213 i=i+1
nicholas@2431 214 s.send_response(200)
nicholas@2431 215 s.send_header("Content-type", "text/xml")
nicholas@2431 216 s.end_headers()
nicholas@2431 217 s.wfile.write(ET.tostring(return_node))
nicholas@2431 218
b@2264 219 def http_do_HEAD(s):
b@2264 220 s.send_response(200)
b@2264 221 s.send_header("Content-type", "text/html")
b@2264 222 s.end_headers()
b@2264 223
b@2264 224 def http_do_GET(request):
nicholas@2450 225 global pseudo_index
b@2264 226 if(request.client_address[0] == "127.0.0.1"):
b@2264 227 if (request.path == "/favicon.ico"):
b@2264 228 send404(request)
b@2264 229 elif (request.path.split('?',1)[0] == "/php/keygen.php"):
b@2264 230 keygen(request);
nicholas@2430 231 elif (request.path.split('?',1)[0] == "/php/pool.php"):
nicholas@2430 232 poolXML(request);
b@2264 233 else:
b@2264 234 request.path = request.path.split('?',1)[0]
b@2264 235 if (request.path == '/'):
b@2264 236 request.path = '/index.html'
b@2264 237 elif (request.path == '/pseudo.xml'):
nicholas@2450 238 request.path = PSEUDO_PATH + pseudo_files[pseudo_index]
b@2264 239 print(request.path)
b@2264 240 pseudo_index += 1
b@2264 241 pseudo_index %= len(pseudo_files)
b@2264 242 processFile(request)
b@2264 243 else:
b@2264 244 send404(request)
b@2264 245
b@2264 246 def http_do_POST(request):
b@2264 247 if(request.client_address[0] == "127.0.0.1"):
b@2264 248 if (request.path.rsplit('?',1)[0] == "/save" or request.path.rsplit('?',1)[0] == "/php/save.php"):
b@2264 249 saveFile(request)
b@2264 250 else:
b@2264 251 send404(request)
b@2264 252
b@2264 253 if sys.version_info[0] == 2:
b@2264 254 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
b@2264 255 def do_HEAD(s):
b@2264 256 http_do_HEAD(s)
b@2264 257 def do_GET(request):
b@2264 258 http_do_GET(request)
b@2264 259 def do_POST(request):
b@2264 260 http_do_POST(request)
b@2264 261 def run(server_class=BaseHTTPServer.HTTPServer,handler_class=MyHandler):
b@2264 262 server_address = ('', 8000)
b@2264 263 httpd = server_class(server_address, handler_class)
b@2264 264 httpd.serve_forever()
b@2264 265 run()
b@2264 266 elif sys.version_info[0] == 3:
b@2264 267 class MyHandler(BaseHTTPRequestHandler):
b@2264 268 def do_HEAD(s):
b@2264 269 send404(s)
b@2264 270 def do_GET(request):
b@2264 271 http_do_GET(request)
b@2264 272 def do_POST(request):
b@2264 273 http_do_POST(request)
b@2264 274 def run(server_class=HTTPServer,handler_class=MyHandler):
b@2264 275 server_address = ('', 8000)
b@2264 276 httpd = server_class(server_address, handler_class)
b@2264 277 httpd.serve_forever()
b@2264 278 run()