Skip to content

Instantly share code, notes, and snippets.

@ssoto
Created July 21, 2016 14:38
Show Gist options
  • Save ssoto/7a5ce9ea6ece709ca2eece032d404d0a to your computer and use it in GitHub Desktop.
Save ssoto/7a5ce9ea6ece709ca2eece032d404d0a to your computer and use it in GitHub Desktop.
Falcon dynamic service creation
# -* coding: utf-8 *-
import json
import traceback
import falcon
class Resource(object):
def __init__(self):
self._set_method_manager()
def __retrieve_setting(self, name):
return self.SERVICE_CONFIG.get(name)
def get_url(self):
url = self.__retrieve_setting('url')
if not url:
raise NotImplementedError()
else:
return url
def _set_method_manager(self):
method = self.__retrieve_setting('method').lower()
print (method, str(self.__class__))
if not method:
raise NotImplementedError(
'method config name is mandatory in SERVICE_CONFIG'
)
else:
if method not in ['get', 'post']:
raise ValueError('Method {} forbidden in this version'.format(
method
))
def wrapper_method(req, res):
try:
print req.method, str(self.__class__)
getattr(instance, 'process')(req, res)
except Exception, e:
print 'Error: {}'.format(e)
traceback.format_exc().splitlines()
res.status = falcon.HTTP_500
req.context['result'] = {'status': 'Internal error'}
method_name = 'on_{}'.format(method)
setattr(self, method_name, wrapper_method)
class ServiceA(Resource):
SERVICE_CONFIG = {
'url': '/post_service',
'method': 'POST'
}
def process(self, req, res):
res.status = falcon.HTTP_200
res.body = json.dumps({
'message': 'POST service running!',
'post_data': req.context['data']
})
class ServiceB(Resource):
SERVICE_CONFIG = {
'url': '/get_service',
'method': 'GET'
}
def process(self, req, res):
res.status = falcon.HTTP_200
res.body = json.dumps(
{'message': 'GET service running!',
'get_params': req.params}
)
api = falcon.API()
services = [ServiceA, ServiceB]
for service in services:
instance = service()
api.add_route(instance.get_url(), instance)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment