forked from mathisonian/simple-testing-server
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple-testing-server.py
More file actions
executable file
·133 lines (103 loc) · 4.13 KB
/
simple-testing-server.py
File metadata and controls
executable file
·133 lines (103 loc) · 4.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env python
from BaseHTTPServer import HTTPServer
from BaseHTTPServer import BaseHTTPRequestHandler
import cgi
import random
import os.path
from os import listdir
PORT = 8003
FILE_PREFIX = ""
if __name__ == "__main__":
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')
parser.add_argument('--path', type=str, dest="PATH",
help='the folder to find the json files')
args = parser.parse_args()
if args.PORT:
PORT = args.PORT
if args.PATH:
FILE_PREFIX = args.PATH
except Exception:
# Could not successfully import argparse or something
pass
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(http_code)
#send headers:
self.send_header("Content-type", "application/json")
# send a blank line to end headers:
self.wfile.write("\n")
self.wfile.write(output)
def do_POST(self):
error=''
if self.path == "/success":
response_code = 200
elif self.path == "/error":
response_code = 500
else:
try:
response_code = int(self.path[1:])
except Exception:
response_code = 201
try:
self.send_response(response_code)
self.wfile.write('Content-Type: application/json\n')
self.wfile.write('Client: %s\n' % str(self.client_address))
self.wfile.write('User-agent: %s\n' % str(self.headers['user-agent']))
self.wfile.write('Path: %s\n' % self.path)
self.end_headers()
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
'CONTENT_TYPE':self.headers['Content-Type'],
})
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():
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)
server.serve_forever()