annotate python/pythonServer.py @ 2430:ad87b0d94fa9

WIP for #68. Need to test some functions on 2.7. Then build the new XML.
author Nicholas Jillings <nicholas.jillings@mail.bcu.ac.uk>
date Tue, 31 May 2016 12:04:31 +0100
parents a7182dbc7fd4
children bae25b417c2c
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
b@2264 13
b@2264 14 if sys.version_info[0] == 2:
b@2264 15 # Version 2.x
b@2264 16 import BaseHTTPServer
b@2264 17 import urllib2
b@2264 18 import urlparse
b@2264 19 elif sys.version_info[0] == 3:
b@2264 20 # Version 3.x
b@2264 21 from http.server import BaseHTTPRequestHandler, HTTPServer
b@2264 22 import urllib as urllib2
b@2264 23
b@2264 24 # Go to right folder.
b@2264 25 scriptdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # script directory
b@2264 26 os.chdir(scriptdir) # does this work?
b@2264 27
b@2264 28 PSEUDO_PATH = '../tests/'
b@2264 29 pseudo_files = []
nicholas@2430 30 for filename in os.listdir(PSEUDO_PATH):
b@2264 31 print(filename)
b@2264 32 if filename.endswith('.xml'):
b@2264 33 pseudo_files.append(filename)
b@2264 34
b@2264 35 curSaveIndex = 0;
b@2264 36 curFileName = 'test-0.xml'
nicholas@2430 37 while(os.path.isfile('../saves/'+curFileName)):
b@2264 38 curSaveIndex += 1;
b@2264 39 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 40
b@2264 41 if len(pseudo_files) > 0:
b@2264 42 pseudo_index = curSaveIndex % len(pseudo_files)
b@2264 43 else:
b@2264 44 pseudo_index = 0
b@2264 45
b@2264 46 print('URL: http://localhost:8000/index.html')
b@2264 47
b@2264 48 def send404(s):
b@2264 49 s.send_response(404)
b@2264 50 s.send_header("Content-type", "text/html")
b@2264 51 s.end_headers()
b@2264 52
b@2264 53 def processFile(s):
b@2264 54 if sys.version_info[0] == 2:
b@2264 55 s.path = s.path.rsplit('?')
b@2264 56 s.path = s.path[0]
b@2264 57 s.path = s.path[1:len(s.path)]
b@2264 58 st = s.path.rsplit(',')
b@2264 59 lenSt = len(st)
b@2264 60 fmt = st[lenSt-1].rsplit('.')
b@2264 61 fpath = "../"+urllib2.unquote(s.path)
b@2264 62 size = path.getsize(fpath)
b@2264 63 fileDump = open(fpath)
b@2264 64 s.send_response(200)
b@2264 65
b@2264 66 if (fmt[1] == 'html'):
b@2264 67 s.send_header("Content-type", 'text/html')
b@2264 68 elif (fmt[1] == 'css'):
b@2264 69 s.send_header("Content-type", 'text/css')
b@2264 70 elif (fmt[1] == 'js'):
b@2264 71 s.send_header("Content-type", 'application/javascript')
b@2264 72 else:
b@2264 73 s.send_header("Content-type", 'application/octet-stream')
b@2264 74 s.send_header("Content-Length", size)
b@2264 75 s.end_headers()
b@2264 76 s.wfile.write(fileDump.read())
b@2264 77 fileDump.close()
b@2264 78 elif sys.version_info[0] == 3:
b@2264 79 s.path = s.path.rsplit('?')
b@2264 80 s.path = s.path[0]
b@2264 81 s.path = s.path[1:len(s.path)]
b@2264 82 st = s.path.rsplit(',')
b@2264 83 lenSt = len(st)
b@2264 84 fmt = st[lenSt-1].rsplit('.')
b@2264 85 fpath = "../"+urllib2.parse.unquote(s.path)
b@2264 86 s.send_response(200)
b@2264 87 if (fmt[1] == 'html'):
b@2264 88 s.send_header("Content-type", 'text/html')
b@2264 89 fileDump = open(fpath, encoding='utf-8')
b@2264 90 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 91 fileDump.close()
b@2264 92 elif (fmt[1] == 'css'):
b@2264 93 s.send_header("Content-type", 'text/css')
b@2264 94 fileDump = open(fpath, encoding='utf-8')
b@2264 95 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 96 fileDump.close()
b@2264 97 elif (fmt[1] == 'js'):
b@2264 98 s.send_header("Content-type", 'application/javascript')
b@2264 99 fileDump = open(fpath, encoding='utf-8')
b@2264 100 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 101 fileDump.close()
b@2264 102 else:
b@2264 103 s.send_header("Content-type", 'application/octet-stream')
b@2264 104 fileDump = open(fpath, 'rb')
b@2264 105 fileBytes = fileDump.read()
b@2264 106 fileDump.close()
b@2264 107 s.send_header("Content-Length", len(fileBytes))
b@2264 108 s.end_headers()
b@2264 109 s.wfile.write(fileBytes)
b@2264 110
b@2264 111 def keygen(s):
b@2264 112 reply = ""
b@2264 113 options = s.path.rsplit('?')
b@2264 114 options = options[1].rsplit('=')
b@2264 115 key = options[1]
b@2264 116 print("Registered key "+key)
b@2264 117 if os.path.isfile("saves/save-"+key+".xml"):
b@2264 118 reply = "<response><state>NO</state><key>"+key+"</key></response>"
b@2264 119 else:
b@2264 120 reply = "<response><state>OK</state><key>"+key+"</key></response>"
b@2264 121 s.send_response(200)
b@2264 122 s.send_header("Content-type", "application/xml")
b@2264 123 s.end_headers()
nicholas@2377 124 if sys.version_info[0] == 2:
nicholas@2377 125 s.wfile.write(reply)
nicholas@2377 126 elif sys.version_info[0] == 3:
nicholas@2377 127 s.wfile.write(bytes(reply, "utf-8"))
b@2264 128 file = open("../saves/save-"+key+".xml",'w')
b@2264 129 file.write("<waetresult key="+key+"/>")
b@2264 130 file.close();
b@2264 131
b@2264 132 def saveFile(self):
b@2264 133 global curFileName
b@2264 134 global curSaveIndex
b@2264 135 options = self.path.rsplit('?')
b@2264 136 options = options[1].rsplit('=')
b@2264 137 key = options[1]
b@2264 138 varLen = int(self.headers['Content-Length'])
b@2264 139 postVars = self.rfile.read(varLen)
b@2264 140 print("Saving file key "+key)
nicholas@2376 141 file = open('../saves/save-'+key+'.xml','wb')
b@2264 142 file.write(postVars)
b@2264 143 file.close()
b@2264 144 try:
b@2264 145 wbytes = os.path.getsize('../saves/save-'+key+'.xml')
b@2264 146 except OSError:
b@2264 147 self.send_response(200)
b@2264 148 self.send_header("Content-type", "text/xml")
b@2264 149 self.end_headers()
b@2264 150 self.wfile.write('<response state="error"><message>Could not open file</message></response>')
b@2264 151 self.send_response(200)
b@2264 152 self.send_header("Content-type", "text/xml")
b@2264 153 self.end_headers()
nicholas@2376 154 reply = '<response state="OK"><message>OK</message><file bytes="'+str(wbytes)+'">"saves/'+curFileName+'"</file></response>'
nicholas@2382 155 if sys.version_info[0] == 2:
nicholas@2382 156 self.wfile.write(reply)
nicholas@2382 157 elif sys.version_info[0] == 3:
nicholas@2382 158 self.wfile.write(bytes(reply, "utf-8"))
b@2264 159 curSaveIndex += 1
b@2264 160 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 161
nicholas@2430 162 def poolXML(s):
nicholas@2430 163 pool = ET.parse('../tests/pool.xml')
nicholas@2430 164 root = pool.getroot()
nicholas@2430 165 setupNode = root.find("setup");
nicholas@2430 166 poolSize = setupNode.get("poolSize",0);
nicholas@2430 167 if (poolSize == 0):
nicholas@2430 168 s.path = s.path.split("/php",1)[0]+"/tests/pool/xml"
nicholas@2430 169 processFile(s)
nicholas@2430 170 return
nicholas@2430 171 # Set up the store will all the test page key nodes
nicholas@2430 172 pages = {};
nicholas@2430 173 for page in root.iter("page"):
nicholas@2430 174 id = page.get("id")
nicholas@2430 175 print(id)
nicholas@2430 176 pages[id] = 0
nicholas@2430 177
nicholas@2430 178 # Read the saves and determine the completed pages
nicholas@2430 179 for filename in os.listdir("../saves/"):
nicholas@2430 180 if filename.endswith(".xml"):
nicholas@2430 181 print("../saves/"+filename)
nicholas@2430 182 save = ET.parse("../saves/"+filename)
nicholas@2430 183 save_root = save.getroot();
nicholas@2430 184 if (save_root.get("url") == s.path):
nicholas@2430 185 for page in save_root.iter("page"):
nicholas@2430 186 id = page.get("id")
nicholas@2430 187 pages[id] = pages[id] + 1
nicholas@2430 188
nicholas@2430 189 # Sort the dictionary
nicholas@2430 190 pages = sorted(pages.items(), key=operator.itemgetter(1))
nicholas@2430 191
b@2264 192 def http_do_HEAD(s):
b@2264 193 s.send_response(200)
b@2264 194 s.send_header("Content-type", "text/html")
b@2264 195 s.end_headers()
b@2264 196
b@2264 197 def http_do_GET(request):
b@2264 198 if(request.client_address[0] == "127.0.0.1"):
b@2264 199 if (request.path == "/favicon.ico"):
b@2264 200 send404(request)
b@2264 201 elif (request.path.split('?',1)[0] == "/php/keygen.php"):
b@2264 202 keygen(request);
nicholas@2430 203 elif (request.path.split('?',1)[0] == "/php/pool.php"):
nicholas@2430 204 poolXML(request);
b@2264 205 else:
b@2264 206 request.path = request.path.split('?',1)[0]
b@2264 207 if (request.path == '/'):
b@2264 208 request.path = '/index.html'
b@2264 209 elif (request.path == '/pseudo.xml'):
b@2264 210 request.path = '/'+PSEUDO_PATH + pseudo_files[pseudo_index]
b@2264 211 print(request.path)
b@2264 212 pseudo_index += 1
b@2264 213 pseudo_index %= len(pseudo_files)
b@2264 214 processFile(request)
b@2264 215 else:
b@2264 216 send404(request)
b@2264 217
b@2264 218 def http_do_POST(request):
b@2264 219 if(request.client_address[0] == "127.0.0.1"):
b@2264 220 if (request.path.rsplit('?',1)[0] == "/save" or request.path.rsplit('?',1)[0] == "/php/save.php"):
b@2264 221 saveFile(request)
b@2264 222 else:
b@2264 223 send404(request)
b@2264 224
b@2264 225 if sys.version_info[0] == 2:
b@2264 226 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
b@2264 227 def do_HEAD(s):
b@2264 228 http_do_HEAD(s)
b@2264 229 def do_GET(request):
b@2264 230 http_do_GET(request)
b@2264 231 def do_POST(request):
b@2264 232 http_do_POST(request)
b@2264 233 def run(server_class=BaseHTTPServer.HTTPServer,handler_class=MyHandler):
b@2264 234 server_address = ('', 8000)
b@2264 235 httpd = server_class(server_address, handler_class)
b@2264 236 httpd.serve_forever()
b@2264 237 run()
b@2264 238 elif sys.version_info[0] == 3:
b@2264 239 class MyHandler(BaseHTTPRequestHandler):
b@2264 240 def do_HEAD(s):
b@2264 241 send404(s)
b@2264 242 def do_GET(request):
b@2264 243 http_do_GET(request)
b@2264 244 def do_POST(request):
b@2264 245 http_do_POST(request)
b@2264 246 def run(server_class=HTTPServer,handler_class=MyHandler):
b@2264 247 server_address = ('', 8000)
b@2264 248 httpd = server_class(server_address, handler_class)
b@2264 249 httpd.serve_forever()
b@2264 250 run()