def on_get(self, req, resp, uni, term):
# The term must be a string since the threads represent them as such
if uni in uniThreads and term in uniThreads[uni].getTerms():
if uniThreads[uni].isScraping:
# we don't want to return data while scraping, send error (configure nginx to send stale data if it can)
resp.status = falcon.HTTP_500
resp.body = json.dumps(
{"error": "We're currently scraping this university, please check back in a couple minutes!"}
).encode('utf-8')
else:
# Get course/subject list
subject_list = json.dumps(uniThreads[uni].getSubjectListAll(term), sort_keys=True).encode('utf-8')
# set the etag and body
resp.etag = "W/" + hashlib.sha1(subject_list).hexdigest()
resp.body = subject_list
else:
# Couldn't find the uni or term, send error
resp.status = falcon.HTTP_400
resp.body = json.dumps(
{"error": "The specified university or term was not found"}
).encode('utf-8')
python类HTTP_500的实例源码
def default_exception_handler(ex, req, resp, params):
"""
Catch-all execption handler for standardized output.
If this is a standard falcon HTTPError, rethrow it for handling
"""
if isinstance(ex, falcon.HTTPError):
# allow the falcon http errors to bubble up and get handled
raise ex
else:
# take care of the uncaught stuff
exc_string = traceback.format_exc()
logging.error('Unhanded Exception being handled: \n%s', exc_string)
format_error_resp(
req,
resp,
falcon.HTTP_500,
error_type=ex.__class__.__name__,
message="Unhandled Exception raised: %s" % str(ex),
retry=True
)
def on_get(self, req, resp):
"""Method handler for GET requests.
:param req: Falcon request object
:param resp: Falcon response object
"""
state = self.state_manager
try:
designs = list(state.designs.keys())
resp.body = json.dumps(designs)
resp.status = falcon.HTTP_200
except Exception as ex:
self.error(req.context, "Exception raised: %s" % str(ex))
self.return_error(
resp,
falcon.HTTP_500,
message="Error accessing design list",
retry=True)
def task_validate_design(self, req, resp, json_data):
"""Create async task for validate design."""
action = json_data.get('action', None)
if action != 'validate_design':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_validate_design"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def task_verify_site(self, req, resp, json_data):
"""Create async task for verify site."""
action = json_data.get('action', None)
if action != 'verify_site':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_verify_site"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def task_prepare_site(self, req, resp, json_data):
"""Create async task for prepare site."""
action = json_data.get('action', None)
if action != 'prepare_site':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_prepare_site"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def task_verify_nodes(self, req, resp, json_data):
"""Create async task for verify node."""
action = json_data.get('action', None)
if action != 'verify_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_verify_nodes"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def task_deploy_nodes(self, req, resp, json_data):
"""Create async task for deploy node."""
action = json_data.get('action', None)
if action != 'deploy_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_deploy_nodes"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def task_destroy_nodes(self, req, resp, json_data):
"""Create async task for destroy node."""
action = json_data.get('action', None)
if action != 'destroy_nodes':
self.error(
req.context,
"Task body ended up in wrong handler: action %s in task_destroy_nodes"
% action)
self.return_error(
resp, falcon.HTTP_500, message="Error", retry=False)
try:
task = self.create_task(json_data, req.context)
resp.body = json.dumps(task.to_dict())
resp.append_header('Location',
"/api/v1.0/tasks/%s" % str(task.task_id))
resp.status = falcon.HTTP_201
except errors.InvalidFormat as ex:
self.error(req.context, ex.msg)
self.return_error(
resp, falcon.HTTP_400, message=ex.msg, retry=False)
def on_get(self, req, resp, task_id):
"""Handler for GET method."""
try:
task = self.state_manager.get_task(uuid.UUID(task_id))
if task is None:
self.info(req.context, "Task %s does not exist" % task_id)
self.return_error(
resp,
falcon.HTTP_404,
message="Task %s does not exist" % task_id,
retry=False)
return
resp.body = json.dumps(task.to_dict())
resp.status = falcon.HTTP_200
except Exception as ex:
self.error(req.context, "Unknown error: %s" % (str(ex)))
self.return_error(
resp, falcon.HTTP_500, message="Unknown error", retry=False)
wechatapiresource.py 文件源码
项目:wechat-bot-skeleton-python
作者: edonosotti
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def on_get(self, request, response):
# Get the parameters from the query string
signature = request.get_param('signature')
timestamp = request.get_param('timestamp')
nonce = request.get_param('nonce')
echostr = request.get_param('echostr')
# Compute the signature (note that the shared token is used too)
verification_elements = [self.token, timestamp, nonce]
verification_elements.sort()
verification_string = "".join(verification_elements)
verification_string = hashlib.sha1(verification_string.encode('utf-8')).hexdigest()
# If the signature is correct, output the same "echostr" provided by the WeChat server as a parameter
if signature == verification_string:
response.status = falcon.HTTP_200
response.body = echostr
else:
response.status = falcon.HTTP_500
response.body = ""
# Messages will be POSTed from the WeChat server to the chatbot backend server,
# see: http://admin.wechat.com/wiki/index.php?title=Common_Messages
def default_exception_handler(ex, req, resp, params):
"""
Catch-all exception handler for standardized output.
If this is a standard falcon HTTPError, rethrow it for handling
"""
if isinstance(ex, falcon.HTTPError):
# allow the falcon http errors to bubble up and get handled
raise ex
else:
# take care of the uncaught stuff
exc_string = traceback.format_exc()
LOG.error('Unhanded Exception being handled: \n%s', exc_string)
format_error_resp(
req,
resp,
falcon.HTTP_500,
error_type=ex.__class__.__name__,
message="Unhandled Exception raised: %s" % str(ex),
retry=True)
def on_get(self, req, resp):
"""
Handles GET requests for ELB HealthCheck Resource
:param req:
:param resp:
:return:
"""
uptime = int(time.time()) - self.start_time
if self.load_balancer.check_if_model_to_workers_map_is_empty():
resp.status = falcon.HTTP_500
resp.body = "Model To Workers Map is Empty"
raise falcon.HTTPInternalServerError('Internal Server Error', 'Model To Workers Map is Empty! ')
resp.status = falcon.HTTP_200
# TODO requests and capacity have to be calculated. They are hardcoded for now
resp.body = json.dumps({'uptime':uptime, 'requests': 1, 'capacity': 100})
def on_post(self, req, resp):
payload = json.loads(req.stream.read())
pi = PredictionInput()
if ('url' in payload.keys()) and ('modelId' in payload.keys()):
pi.url = payload['url']
pi.model_id = payload['modelId']
else:
resp.status = falcon.HTTP_400
raise falcon.HTTPBadRequest("Bad Request", "Url and(or) modelId missing in the payload")
po = self.caffe_worker_client.predict(pi)
if po.bo.status == 'Success':
resp.status = falcon.HTTP_200
resp.body = (str(po.values))
elif po.bo.status == 'Failure':
resp.body = json.dumps({'status': 'Failure', 'message' : 'Error occurred'})
resp.status = falcon.HTTP_500
raise falcon.HTTPInternalServerError('Internal Server Error', 'Predict failed! ')
def default_error_handler(req, resp, e):
resp.body = json.dumps({'title': str(type(e)), 'description': str(e)}, indent=2, ensure_ascii=False)
resp.status = falcon.HTTP_500
resp.content_type = 'application/json'
# def http_not_found_handler(req, resp, e):
# resp.body = e.title
# resp.status = e.status
# resp.content_type = 'application/json'
#
#
# def http_missing_param_handler(req, resp, e):
# resp.body = json.dumps({'error': e.title + ':' + ' '.join([p for p in e.args])})
# resp.status = e.status
# resp.content_type = 'application/json'
#
#
# def http_invalid_param_handler(req, resp, e):
# resp.body = json.dumps({'error': e.title + ':' + ' '.join([p for p in e.args])})
# resp.status = e.status
# resp.content_type = 'application/json'
def on_get(self, req, resp):
'''
get tiller status
'''
try:
opts = req.params
tiller = Tiller(
tiller_host=opts.get('tiller_host', None),
tiller_port=opts.get('tiller_port', None))
message = {
'tiller': {
'state': tiller.tiller_status(),
'version': tiller.tiller_version()
}
}
resp.status = falcon.HTTP_200
resp.body = json.dumps(message)
resp.content_type = 'application/json'
except Exception as e:
err_message = 'Failed to get Tiller Status: {}'.format(e)
self.error(req.context, err_message)
self.return_error(
resp, falcon.HTTP_500, message=err_message)
def on_get(self, req, resp):
'''
get tiller releases
'''
try:
# Get tiller releases
opts = req.params
tiller = Tiller(tiller_host=opts.get('tiller_host', None),
tiller_port=opts.get('tiller_port', None))
releases = {}
for release in tiller.list_releases():
if not releases.get(release.namespace, None):
releases[release.namespace] = []
releases[release.namespace].append(release.name)
resp.body = json.dumps({'releases': releases})
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200
except Exception as e:
err_message = 'Unable to find Tiller Releases: {}'.format(e)
self.error(req.context, err_message)
self.return_error(
resp, falcon.HTTP_500, message=err_message)
def on_get(self, req, resp, release):
try:
self.logger.info('RUNNING: %s', release)
opts = req.params
tiller = Tiller(tiller_host=opts.get('tiller_host', None),
tiller_port=opts.get('tiller_port', None))
tiller_resp = tiller.testing_release(release)
msg = {
'result': '',
'message': ''
}
if tiller_resp:
test_status = getattr(
tiller_resp.info.status, 'last_test_suite_run', 'FAILED')
if test_status.result[0].status:
msg['result'] = 'PASSED: {}'.format(release)
msg['message'] = 'MESSAGE: Test Pass'
self.logger.info(msg)
else:
msg['result'] = 'FAILED: {}'.format(release)
msg['message'] = 'MESSAGE: Test Fail'
self.logger.info(msg)
else:
msg['result'] = 'FAILED: {}'.format(release)
msg['message'] = 'MESSAGE: No test found'
resp.body = json.dumps(msg)
resp.status = falcon.HTTP_200
resp.content_type = 'application/json'
except Exception as e:
err_message = 'Failed to test {}: {}'.format(release, e)
self.error(req.context, err_message)
self.return_error(
resp, falcon.HTTP_500, message=err_message)
def on_get(self, req, resp):
resp.status = falcon.HTTP_500
resp.set_header('X-Failed', 'True')
resp.body = 'Fail'
def on_post(self, req, resp):
resp.status = falcon.HTTP_500
resp.set_header('X-Failed', 'True')
resp.body = 'Fail'
raise HTTPStatus(falcon.HTTP_200,
headers={'X-Failed': 'False'},
body='Pass')
def on_get(self, req, resp):
resp.status = falcon.HTTP_500
resp.set_header('X-Failed', 'True')
resp.body = 'Fail'
def test_misc(self, client):
self._misc_test(client, falcon.HTTPBadRequest, falcon.HTTP_400)
self._misc_test(client, falcon.HTTPNotAcceptable, falcon.HTTP_406,
needs_title=False)
self._misc_test(client, falcon.HTTPConflict, falcon.HTTP_409)
self._misc_test(client, falcon.HTTPPreconditionFailed, falcon.HTTP_412)
self._misc_test(client, falcon.HTTPUnsupportedMediaType, falcon.HTTP_415,
needs_title=False)
self._misc_test(client, falcon.HTTPUnprocessableEntity, falcon.HTTP_422)
self._misc_test(client, falcon.HTTPUnavailableForLegalReasons, falcon.HTTP_451,
needs_title=False)
self._misc_test(client, falcon.HTTPInternalServerError, falcon.HTTP_500)
self._misc_test(client, falcon.HTTPBadGateway, falcon.HTTP_502)
def on_get(self, req, resp):
try:
maas_client = MaasRequestFactory(
config.config_mgr.conf.maasdriver.maas_api_url,
config.config_mgr.conf.maasdriver.maas_api_key)
machine_list = Machines(maas_client)
machine_list.refresh()
node_view = list()
for m in machine_list:
m.get_power_params()
node_view.append(
dict(
hostname=m.hostname,
memory=m.memory,
cpu_count=m.cpu_count,
status_name=m.status_name,
boot_mac=m.boot_mac,
power_state=m.power_state,
power_address=m.power_parameters.get('power_address'),
boot_ip=m.boot_ip))
resp.body = json.dumps(node_view)
resp.status = falcon.HTTP_200
except Exception as ex:
self.error(req.context, "Unknown error: %s" % str(ex), exc_info=ex)
self.return_error(
resp, falcon.HTTP_500, message="Unknown error", retry=False)
def on_post(self, req, resp):
"""Method handler for POST requests.
:param req: Falcon request object
:param resp: Falcon response object
"""
try:
json_data = self.req_json(req)
design = None
if json_data is not None:
base_design = json_data.get('base_design_id', None)
if base_design is not None:
base_design = uuid.UUID(base_design)
design = hd_objects.SiteDesign(base_design_id=base_design)
else:
design = hd_objects.SiteDesign()
design.assign_id()
design.create(req.context, self.state_manager)
resp.body = json.dumps(design.obj_to_simple())
resp.status = falcon.HTTP_201
except errors.StateError:
self.error(req.context, "Error updating persistence")
self.return_error(
resp,
falcon.HTTP_500,
message="Error updating persistence",
retry=True)
except errors.InvalidFormat as fex:
self.error(req.context, str(fex))
self.return_error(
resp, falcon.HTTP_400, message=str(fex), retry=False)
def on_get(self, req, resp, design_id, kind, name):
source = req.params.get('source', 'designed')
try:
design = None
if source == 'compiled':
design = self.orchestrator.get_effective_site(design_id)
elif source == 'designed':
design = self.orchestrator.get_described_site(design_id)
part = None
if kind == 'Site':
part = design.get_site()
elif kind == 'Network':
part = design.get_network(name)
elif kind == 'NetworkLink':
part = design.get_network_link(name)
elif kind == 'HardwareProfile':
part = design.get_hardware_profile(name)
elif kind == 'HostProfile':
part = design.get_host_profile(name)
elif kind == 'BaremetalNode':
part = design.get_baremetal_node(name)
else:
self.error(req.context, "Kind %s unknown" % kind)
self.return_error(
resp,
falcon.HTTP_404,
message="Kind %s unknown" % kind,
retry=False)
return
resp.body = json.dumps(part.obj_to_simple())
except errors.DesignError as dex:
self.error(req.context, str(dex))
self.return_error(
resp, falcon.HTTP_404, message=str(dex), retry=False)
except Exception as exc:
self.error(req.context, str(exc))
self.return_error(
resp.falcon.HTTP_500, message=str(exc), retry=False)
def on_post(self, req, resp):
"""Handler for POST method."""
# A map of supported actions to the handlers for tasks for those actions
supported_actions = {
'validate_design': TasksResource.task_validate_design,
'verify_site': TasksResource.task_verify_site,
'prepare_site': TasksResource.task_prepare_site,
'verify_nodes': TasksResource.task_verify_nodes,
'prepare_nodes': TasksResource.task_prepare_nodes,
'deploy_nodes': TasksResource.task_deploy_nodes,
'destroy_nodes': TasksResource.task_destroy_nodes,
}
try:
json_data = self.req_json(req)
action = json_data.get('action', None)
if supported_actions.get(action, None) is None:
self.error(req.context, "Unsupported action %s" % action)
self.return_error(
resp,
falcon.HTTP_400,
message="Unsupported action %s" % action,
retry=False)
else:
supported_actions.get(action)(self, req, resp, json_data)
except Exception as ex:
self.error(req.context, "Unknown error: %s\n%s" %
(str(ex), traceback.format_exc()))
self.return_error(
resp, falcon.HTTP_500, message="Unknown error", retry=False)
def on_get(self, req, resp, **kwargs):
resp.status = falcon.HTTP_500
resp.body = 'Failure'
def post_excp(req, resp, error):
if type(error) == CustomException:
resp.body = json.dumps({
'error': 'hahah'
})
resp.status = falcon.HTTP_500
# raise error
def sink(req, resp):
do_log_history(req, resp)
paths = filter(lambda x: x != '', req.path.split('/'))
ctrl_name = func_name = 'index'
if len(paths) >= 2:
ctrl_name = paths[0]
func_name = paths[1]
elif len(paths) == 1:
func_name = paths[0]
ctrl = loader.ctrl(ctrl_name)
if ctrl == None or not hasattr(ctrl, func_name):
resp.status = falcon.HTTP_404
resp.body = "Not Found"
else:
try:
content = getattr(ctrl, func_name)(req, resp)
if resp.body == None:
if isinstance(content, unicode):
resp.body = unicode.encode(content, 'utf-8', 'ignore')
elif isinstance(content, str):
resp.body = content
else:
resp.body = json.dumps(content)
except Exception as ex:
log_error(ex)
resp.status = falcon.HTTP_500
resp.body = str(ex)
#resp.body = 'A server error occurred. Please contact the administrator'
do_log_result(req, resp)
def on_post(self, req, resp):
try:
# Load data from request and get options
data = list(self.req_yaml(req))
if type(data[0]) is list:
data = list(data[0])
opts = req.params
# Encode filename
armada = Armada(
data,
disable_update_pre=req.get_param_as_bool(
'disable_update_pre'),
disable_update_post=req.get_param_as_bool(
'disable_update_post'),
enable_chart_cleanup=req.get_param_as_bool(
'enable_chart_cleanup'),
dry_run=req.get_param_as_bool('dry_run'),
wait=req.get_param_as_bool('wait'),
timeout=int(opts.get('timeout', 3600)),
tiller_host=opts.get('tiller_host', None),
tiller_port=int(opts.get('tiller_port', 44134)),
)
msg = armada.sync()
resp.body = json.dumps(
{
'message': msg,
}
)
resp.content_type = 'application/json'
resp.status = falcon.HTTP_200
except Exception as e:
err_message = 'Failed to apply manifest: {}'.format(e)
self.error(req.context, err_message)
self.return_error(
resp, falcon.HTTP_500, message=err_message)