This repository has been archived by the owner on Aug 27, 2023. It is now read-only.
/
__init__.py
69 lines (56 loc) · 2.06 KB
/
__init__.py
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
""" Views """
import logging
import traceback
from pyramid.httpexceptions import HTTPException, HTTPServerError
from pyramid.settings import asbool
from pyramid.view import view_config
from pyramid_duh import addslash
from pypicloud import __version__
from pypicloud.route import Root
LOG = logging.getLogger(__name__)
@view_config(context=Root, request_method="GET", subpath=(), renderer="base.jinja2")
@addslash
def get_index(request):
"""Render a home screen"""
return {"version": __version__}
@view_config(route_name="health", renderer="json")
def health_endpoint(request):
"""Simple health endpoint"""
ret = {}
ok, ret["access"] = request.access.check_health()
if not ok:
request.response.status = 500
ok, ret["cache"] = request.db.check_health()
if not ok:
request.response.status = 500
ok, ret["storage"] = request.db.storage.check_health()
if not ok:
request.response.status = 500
return ret
@view_config(context=Exception, renderer="json")
@view_config(context=HTTPException, renderer="json")
def format_exception(context, request):
"""
Catch all app exceptions and render them nicely
This will keep the status code, but will always return parseable json
Returns
-------
error : str
Identifying error key
message : str
Human-readable error message
stacktrace : str, optional
If pyramid.debug = true, also return the stacktrace to the client
"""
message = context.message if hasattr(context, "message") else str(context)
LOG.exception(message)
if not request.path.startswith("/api/") and not request.path.startswith("/admin/"):
if isinstance(context, HTTPException):
return context
else:
return HTTPServerError(message)
error = {"error": getattr(context, "error", "unknown"), "message": message}
if asbool(request.registry.settings.get("pyramid.debug", False)):
error["stacktrace"] = traceback.format_exc()
request.response.status_code = getattr(context, "status_code", 500)
return error