annotate python/pythonServer.py @ 2376:c41caaa96633

Some fixes for #90. Also a failsafe loop if the server never responds with meaningul information from saves (for instance, running only on apache or basic http servers). More changes to pythonServer for python 3.5. Please check if still valid on 2.7
author Nicholas Jillings <nicholas.jillings@mail.bcu.ac.uk>
date Thu, 19 May 2016 10:44:19 +0100
parents 556b79c72eee
children e04f0f8b6f8f
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 from os import walk
b@2264 8 from os import path
b@2264 9 from os import listdir
b@2264 10 import inspect
b@2264 11 import os
b@2264 12 import pickle
b@2264 13 import datetime
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 = []
b@2264 31 for filename in listdir(PSEUDO_PATH):
b@2264 32 print(filename)
b@2264 33 if filename.endswith('.xml'):
b@2264 34 pseudo_files.append(filename)
b@2264 35
b@2264 36 curSaveIndex = 0;
b@2264 37 curFileName = 'test-0.xml'
b@2264 38 while(path.isfile('../saves/'+curFileName)):
b@2264 39 curSaveIndex += 1;
b@2264 40 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 41
b@2264 42 if len(pseudo_files) > 0:
b@2264 43 pseudo_index = curSaveIndex % len(pseudo_files)
b@2264 44 else:
b@2264 45 pseudo_index = 0
b@2264 46
b@2264 47 print('URL: http://localhost:8000/index.html')
b@2264 48
b@2264 49 def send404(s):
b@2264 50 s.send_response(404)
b@2264 51 s.send_header("Content-type", "text/html")
b@2264 52 s.end_headers()
b@2264 53
b@2264 54 def processFile(s):
b@2264 55 if sys.version_info[0] == 2:
b@2264 56 s.path = s.path.rsplit('?')
b@2264 57 s.path = s.path[0]
b@2264 58 s.path = s.path[1:len(s.path)]
b@2264 59 st = s.path.rsplit(',')
b@2264 60 lenSt = len(st)
b@2264 61 fmt = st[lenSt-1].rsplit('.')
b@2264 62 fpath = "../"+urllib2.unquote(s.path)
b@2264 63 size = path.getsize(fpath)
b@2264 64 fileDump = open(fpath)
b@2264 65 s.send_response(200)
b@2264 66
b@2264 67 if (fmt[1] == 'html'):
b@2264 68 s.send_header("Content-type", 'text/html')
b@2264 69 elif (fmt[1] == 'css'):
b@2264 70 s.send_header("Content-type", 'text/css')
b@2264 71 elif (fmt[1] == 'js'):
b@2264 72 s.send_header("Content-type", 'application/javascript')
b@2264 73 else:
b@2264 74 s.send_header("Content-type", 'application/octet-stream')
b@2264 75 s.send_header("Content-Length", size)
b@2264 76 s.end_headers()
b@2264 77 s.wfile.write(fileDump.read())
b@2264 78 fileDump.close()
b@2264 79 elif sys.version_info[0] == 3:
b@2264 80 s.path = s.path.rsplit('?')
b@2264 81 s.path = s.path[0]
b@2264 82 s.path = s.path[1:len(s.path)]
b@2264 83 st = s.path.rsplit(',')
b@2264 84 lenSt = len(st)
b@2264 85 fmt = st[lenSt-1].rsplit('.')
b@2264 86 fpath = "../"+urllib2.parse.unquote(s.path)
b@2264 87 s.send_response(200)
b@2264 88 if (fmt[1] == 'html'):
b@2264 89 s.send_header("Content-type", 'text/html')
b@2264 90 fileDump = open(fpath, encoding='utf-8')
b@2264 91 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 92 fileDump.close()
b@2264 93 elif (fmt[1] == 'css'):
b@2264 94 s.send_header("Content-type", 'text/css')
b@2264 95 fileDump = open(fpath, encoding='utf-8')
b@2264 96 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 97 fileDump.close()
b@2264 98 elif (fmt[1] == 'js'):
b@2264 99 s.send_header("Content-type", 'application/javascript')
b@2264 100 fileDump = open(fpath, encoding='utf-8')
b@2264 101 fileBytes = bytes(fileDump.read(), "utf-8")
b@2264 102 fileDump.close()
b@2264 103 else:
b@2264 104 s.send_header("Content-type", 'application/octet-stream')
b@2264 105 fileDump = open(fpath, 'rb')
b@2264 106 fileBytes = fileDump.read()
b@2264 107 fileDump.close()
b@2264 108 s.send_header("Content-Length", len(fileBytes))
b@2264 109 s.end_headers()
b@2264 110 s.wfile.write(fileBytes)
b@2264 111
b@2264 112 def keygen(s):
b@2264 113 reply = ""
b@2264 114 options = s.path.rsplit('?')
b@2264 115 options = options[1].rsplit('=')
b@2264 116 key = options[1]
b@2264 117 print("Registered key "+key)
b@2264 118 if os.path.isfile("saves/save-"+key+".xml"):
b@2264 119 reply = "<response><state>NO</state><key>"+key+"</key></response>"
b@2264 120 else:
b@2264 121 reply = "<response><state>OK</state><key>"+key+"</key></response>"
b@2264 122 s.send_response(200)
b@2264 123 s.send_header("Content-type", "application/xml")
b@2264 124 s.end_headers()
nicholas@2376 125 s.wfile.write(bytes(reply, "utf-8"))
b@2264 126 file = open("../saves/save-"+key+".xml",'w')
b@2264 127 file.write("<waetresult key="+key+"/>")
b@2264 128 file.close();
b@2264 129
b@2264 130 def saveFile(self):
b@2264 131 global curFileName
b@2264 132 global curSaveIndex
b@2264 133 options = self.path.rsplit('?')
b@2264 134 options = options[1].rsplit('=')
b@2264 135 key = options[1]
b@2264 136 varLen = int(self.headers['Content-Length'])
b@2264 137 postVars = self.rfile.read(varLen)
b@2264 138 print("Saving file key "+key)
nicholas@2376 139 file = open('../saves/save-'+key+'.xml','wb')
b@2264 140 file.write(postVars)
b@2264 141 file.close()
b@2264 142 try:
b@2264 143 wbytes = os.path.getsize('../saves/save-'+key+'.xml')
b@2264 144 except OSError:
b@2264 145 self.send_response(200)
b@2264 146 self.send_header("Content-type", "text/xml")
b@2264 147 self.end_headers()
b@2264 148 self.wfile.write('<response state="error"><message>Could not open file</message></response>')
b@2264 149 self.send_response(200)
b@2264 150 self.send_header("Content-type", "text/xml")
b@2264 151 self.end_headers()
nicholas@2376 152 reply = '<response state="OK"><message>OK</message><file bytes="'+str(wbytes)+'">"saves/'+curFileName+'"</file></response>'
nicholas@2376 153 self.wfile.write(bytes(reply, "utf-8"))
b@2264 154 curSaveIndex += 1
b@2264 155 curFileName = 'test-'+str(curSaveIndex)+'.xml'
b@2264 156
b@2264 157 def http_do_HEAD(s):
b@2264 158 s.send_response(200)
b@2264 159 s.send_header("Content-type", "text/html")
b@2264 160 s.end_headers()
b@2264 161
b@2264 162 def http_do_GET(request):
b@2264 163 if(request.client_address[0] == "127.0.0.1"):
b@2264 164 if (request.path == "/favicon.ico"):
b@2264 165 send404(request)
b@2264 166 elif (request.path.split('?',1)[0] == "/php/keygen.php"):
b@2264 167 keygen(request);
b@2264 168 else:
b@2264 169 request.path = request.path.split('?',1)[0]
b@2264 170 if (request.path == '/'):
b@2264 171 request.path = '/index.html'
b@2264 172 elif (request.path == '/pseudo.xml'):
b@2264 173 request.path = '/'+PSEUDO_PATH + pseudo_files[pseudo_index]
b@2264 174 print(request.path)
b@2264 175 pseudo_index += 1
b@2264 176 pseudo_index %= len(pseudo_files)
b@2264 177 processFile(request)
b@2264 178 else:
b@2264 179 send404(request)
b@2264 180
b@2264 181 def http_do_POST(request):
b@2264 182 if(request.client_address[0] == "127.0.0.1"):
b@2264 183 if (request.path.rsplit('?',1)[0] == "/save" or request.path.rsplit('?',1)[0] == "/php/save.php"):
b@2264 184 saveFile(request)
b@2264 185 else:
b@2264 186 send404(request)
b@2264 187
b@2264 188 if sys.version_info[0] == 2:
b@2264 189 class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
b@2264 190 def do_HEAD(s):
b@2264 191 http_do_HEAD(s)
b@2264 192 def do_GET(request):
b@2264 193 http_do_GET(request)
b@2264 194 def do_POST(request):
b@2264 195 http_do_POST(request)
b@2264 196 def run(server_class=BaseHTTPServer.HTTPServer,handler_class=MyHandler):
b@2264 197 server_address = ('', 8000)
b@2264 198 httpd = server_class(server_address, handler_class)
b@2264 199 httpd.serve_forever()
b@2264 200 run()
b@2264 201 elif sys.version_info[0] == 3:
b@2264 202 class MyHandler(BaseHTTPRequestHandler):
b@2264 203 def do_HEAD(s):
b@2264 204 send404(s)
b@2264 205 def do_GET(request):
b@2264 206 http_do_GET(request)
b@2264 207 def do_POST(request):
b@2264 208 http_do_POST(request)
b@2264 209 def run(server_class=HTTPServer,handler_class=MyHandler):
b@2264 210 server_address = ('', 8000)
b@2264 211 httpd = server_class(server_address, handler_class)
b@2264 212 httpd.serve_forever()
b@2264 213 run()