json middleware

This commit is contained in:
deflax 2016-04-08 17:48:18 +03:00
parent 22d2412627
commit 6d5ae74495
2 changed files with 84 additions and 15 deletions

View file

@ -53,6 +53,7 @@ def setencpasswd(clientemail, newpass):
query = clientsdb[c_id]['email']
#ioconfig.logger.info('client[{}]> path={}'.format(c_id, str(path)))
except:
ioconfig.logger.critical('clients> client {} not found'.format(clientemail))
raise
if query != clientemail:
@ -122,7 +123,7 @@ def vmowner(vmid, vmname, verbose):
clientid = '0' #unknown owner
clientname = 'unknown'
if verbose:
ioconfig.logger.info('client[{}]> {} is the owner of {} ({})'.fotmat(str(clientid), clientname, str(vmid), vmname))
ioconfig.logger.info('client[{}]> {} is the owner of {} ({})'.format(str(clientid), clientname, str(vmid), vmname))
return clientid
@ -147,5 +148,5 @@ def writeclientsdb(clientsdb):
if __name__ == '__main__':
#setencpasswd('abc@xyz.com', 'todos')
setencpasswd('abc@xyz.com', 'todos')

View file

@ -27,6 +27,65 @@ def welcome():
logger.info('###################################')
class RequireJSON(object):
def process_request(self, req, resp):
if not req.client_accepts_json:
raise falcon.HTTPNotAcceptable(
'This API only supports responses encoded as JSON.',
href='http://docs.examples.com/api/json')
if req.method in ('POST', 'PUT'):
if 'application/json' not in req.content_type:
raise falcon.HTTPUnsupportedMediaType(
'This API only supports requests encoded as JSON.',
href='http://docs.examples.com/api/json')
class JSONTranslator(object):
def process_request(self, req, resp):
# req.stream corresponds to the WSGI wsgi.input environ variable,
# and allows you to read bytes from the request body.
#
# See also: PEP 3333
if req.content_length in (None, 0):
# Nothing to do
return
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body',
'A valid JSON document is required.')
try:
req.context['doc'] = json.loads(body.decode('utf-8'))
except (ValueError, UnicodeDecodeError):
raise falcon.HTTPError(falcon.HTTP_753,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect or not encoded as '
'UTF-8.')
def process_response(self, req, resp, resource):
if 'result' not in req.context:
return
resp.body = json.dumps(req.context['result'])
def max_body(limit):
def hook(req, resp, resource, params):
length = req.content_length
if length is not None and length > limit:
msg = ('The size of the request is too large. The body must not '
'exceed ' + str(limit) + ' bytes in length.')
raise falcon.HTTPRequestEntityTooLarge(
'Request body is too large', msg)
return hook
def apicheck(params):
""" compares request params for api key with the config file"""
try:
@ -47,21 +106,27 @@ def apicheck(params):
#API methods
class Validate(object):
class ValidateResource(object):
@falcon.before(max_body(64 * 1024))
def on_post(self, req, resp):
""" get clientemail and password and compare it with the client db and returns a list of managed object IDs """
clientemail = req.params['clientemail']
passwd = req.params['password']
resp.status = falcon.HTTP_200
clientemail = req.context['doc']['clientemail']
passwd = req.context['doc']['password']
logger.info('grid> access requested for {} with {}'.format(clientemail, passwd))
#apicheck_stat, apicheck_resp = apicheck(req.params)
response = clientsdb.validate(clientemail, passwd)
if response is not None:
resp.status = falcon.HTTP_200
resp.body = response
else:
resp.status = falcon.HTTP_403
resp.body = 'ERR'
print(response)
req.context['result'] = response
#if response is not None:
# resp.status = falcon.HTTP_200
# resp.body = response
#else:
# resp.status = falcon.HTTP_403
# resp.body = 'ERR'
#return response
class ClusterResource(object):
def on_get(self, req, resp):
@ -257,7 +322,10 @@ if __name__ == '__main__':
sys.exit("invoke proxmaster via uwsgi. thanks. bye. o/")
#setup routes
wsgi_app = api = application = falcon.API()
wsgi_app = api = application = falcon.API(middleware=[
RequireJSON(),
JSONTranslator(),
])
#display motd
welcome()
@ -265,8 +333,8 @@ welcome()
#grid.sync()
# setup routes
res_validate = Validate()
api.add_route('/instance/auth', res_validate)
res_validate = ValidateResource()
api.add_route('/validate', res_validate)
res_cluster = ClusterResource()
api.add_route('/instance', res_cluster)