Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ More generally, ```GET http://localhost:<PORT>/<model_name>``` will return an ``
with content taken from a file called ```<model_name>.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 ```<model_name>.json``` does not exist, but a directory with the name ```<model_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:
Expand Down Expand Up @@ -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:<PORT>/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:<PORT>/abc/[same random number] to get back this result

There you have it.

Expand Down
68 changes: 54 additions & 14 deletions simple-testing-server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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')
Expand All @@ -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":
Expand All @@ -66,27 +95,38 @@ def do_POST(self):

self.end_headers()


form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'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)
Expand Down