import json
def HandleRequest(req, state) :
echoheaders = {}
print (req.headers.get('Host', None))
print (req.headers.get('Content-Type', None))
for k, v in req.headers.items() :
echoheaders[k] = v
req.send_response(200)
req.send_header('Content-type', 'Application/json')
req.end_headers()
jsonstr = json.dumps(echoheaders)
req.wfile.write(jsonstr.encode())
req.wfile.flush()
Get Request Query Parameter
import json
import urllib
def HandleRequest(req, state) :
allqueries = urllib.parse.parse_qs(urllib.parse.urlparse(req.path).query)
for k, v in allqueries :
print (k + "=" + v + "\n")
jsonstr = json.dumps(allqueries)
req.send_response(200)
req.send_header('Content-type', 'Application/json')
req.end_headers()
req.wfile.write(jsonstr.encode())
req.wfile.flush()
Get Path Parameter
import json
def HandleRequest(req, state) :
echoparams = {}
print (req.params)
print (req.params.get('group', None))
print (req.params.get('name', None))
for k, v in req.params.items():
echoparams[k] = v
req.send_response(200)
req.send_header('Content-type', 'Application/json')
req.end_headers()
jsonstr = json.dumps(echoparams)
req.wfile.write(jsonstr.encode())
req.wfile.flush()
def HandleRequest(req, state) :
req.send_response(200)
req.send_header('Content-type', 'text/html')
req.send_header('aaaa', 'bbbb')
req.send_header('cccc', 'dddd')
req.end_headers()
req.wfile.write("\nwelcome to advanced Mock Handler\n".encode())
req.wfile.flush()
Response Redirect
def HandleRequest(req, state) :
req.redirect("http://www.google.com")
Response text body
def HandleRequest(req, state) :
req.send_response(200)
req.send_header('Content-type', 'text/html')
req.end_headers()
req.wfile.write("\nwelcome to advanced Mock Handler\n".encode())
req.wfile.flush()
Response Json body
import json
def HandleRequest(req, state) :
data = {
'hello': 'world',
'count': 10,
'array': ["aaa", "bbb", "ccc"]
}
jsonstr = json.dumps(data)
req.send_response(200)
req.send_header('Content-type', 'Application/json')
req.end_headers()
req.wfile.write(jsonstr.encode())
req.wfile.flush()
Get/Set State DB
def HandleRequest(req, state) :
mycounter = state.get("counter")
if mycounter == None:
mycounter = {
'counter' :1,
}
else:
mycounter['counter'] = mycounter['counter'] + 1
state.save("counter", mycounter)
req.send_response(200)
req.send_header('Content-type', 'text/html')
req.end_headers()
req.wfile.write("\nwelcome to advanced Mock Handler\n".encode())
req.wfile.write(str(mycounter['counter']).encode())
req.wfile.flush()