diff --git a/README.md b/README.md index 6df5c6a..8bebd7b 100644 --- a/README.md +++ b/README.md @@ -35,6 +35,9 @@ More generally, ```GET http://localhost:/``` will return an `` with content taken from a file called ```.json``` placed in the same folder as the script. BYO example json files. (use the ```--path``` options if these files are in a different directory) +if a file ```.json``` does not exist, but a directory with the name `````` does. The code will list all files with .json +extension and return a json list with the file names with the .json extension removed + ### POST To make a post request with a successfull (200) response: @@ -64,6 +67,14 @@ The result is parsed and returned back as JSON "p1":"v1" } + +Persistence +--- + +All post requests will be persisted on disk. For example if a post is made to http://localhost:/abc, the code will try to create a file +[random number].json with the content of what POST request also sends back to the client. + +The client can then later request http://localhost:/abc/[same random number] to get back this result There you have it. diff --git a/simple-testing-server.py b/simple-testing-server.py index 8482b3d..ca3985f 100755 --- a/simple-testing-server.py +++ b/simple-testing-server.py @@ -2,6 +2,9 @@ from BaseHTTPServer import HTTPServer from BaseHTTPServer import BaseHTTPRequestHandler import cgi +import random +import os.path +from os import listdir PORT = 8003 @@ -11,6 +14,8 @@ try: import argparse + #random.seed() + parser = argparse.ArgumentParser(description='A simple fake server for testing your API client.') parser.add_argument('-p', '--port', type=int, dest="PORT", help='the port to run the server on; defaults to 8003') @@ -33,20 +38,44 @@ class JSONRequestHandler (BaseHTTPRequestHandler): def do_GET(self): + folder_path=FILE_PREFIX + "/" + self.path[1:] + file_path=folder_path+ ".json" + + http_code=200 + + if os.path.isfile(file_path): + try: + output = open(file_path, 'r').read() + except Exception: + output = "{'error': 'Could not find file " + self.path[1:] + ".json'" + "}" + http_code=404 + elif os.path.isdir(folder_path): + only_files = [ f for f in listdir(folder_path) if os.path.isfile(os.path.join(folder_path,f)) ] + output='[\n' + is_first=True + for f in only_files: + if os.path.splitext(f)[1] == '.json': + output+=('' if is_first else ',\n')+'%s' % (os.path.splitext(f)[0]) + is_first=False + output+=']\n' + else: + http_code=404 + output='{"error":"path does not exist"}' + + #send response code: - self.send_response(200) + self.send_response(http_code) #send headers: self.send_header("Content-type", "application/json") # send a blank line to end headers: self.wfile.write("\n") - try: - output = open(FILE_PREFIX + "/" + self.path[1:] + ".json", 'r').read() - except Exception: - output = "{'error': 'Could not find file " + self.path[1:] + ".json'" + "}" self.wfile.write(output) def do_POST(self): + + error='' + if self.path == "/success": response_code = 200 elif self.path == "/error": @@ -66,7 +95,6 @@ def do_POST(self): self.end_headers() - form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, @@ -74,19 +102,31 @@ def do_POST(self): 'CONTENT_TYPE':self.headers['Content-Type'], }) - self.wfile.write('{\n') - first_key=True + object_id = random.randint(0, 500000000) + + try: + #also write to disk + file_path=FILE_PREFIX + "/" + self.path[1:] +"/" + str(object_id) + ".json" + disk_storage = open (file_path, 'a') + except Exception as e: + error='can\'t create file at %s' % (file_path) + raise + + self.wfile.write('{\n"id":%i' % object_id) + disk_storage.write('{\n"id"=%i' % object_id) for field in form.keys(): - if not first_key: - self.wfile.write(',\n') - else: - self.wfile.write('\n') - first_key=False - self.wfile.write('"%s":"%s"' % (field, form[field].value)) + json_line=',\n"%s":"%s"' % (field, form[field].value) + self.wfile.write(json_line) + disk_storage.write(json_line) self.wfile.write('\n}') + disk_storage.write('\n}') + disk_storage.close + except Exception as e: self.send_response(500) + self.wfile.write(error) + raise server = HTTPServer(("localhost", PORT), JSONRequestHandler)