Package cherrypy :: Package tutorial :: Module tut10_http_errors
[hide private]
[frames] | no frames]

Source Code for Module cherrypy.tutorial.tut10_http_errors

 1  """ 
 2   
 3  Tutorial: HTTP errors 
 4   
 5  HTTPError is used to return an error response to the client. 
 6  CherryPy has lots of options regarding how such errors are 
 7  logged, displayed, and formatted. 
 8   
 9  """ 
10   
11  import os 
12  localDir = os.path.dirname(__file__) 
13  curpath = os.path.normpath(os.path.join(os.getcwd(), localDir)) 
14   
15  import cherrypy 
16   
17   
18 -class HTTPErrorDemo(object):
19 20 # Set a custom response for 403 errors. 21 _cp_config = {'error_page.403': 22 os.path.join(curpath, "custom_error.html")} 23
24 - def index(self):
25 # display some links that will result in errors 26 tracebacks = cherrypy.request.show_tracebacks 27 if tracebacks: 28 trace = 'off' 29 else: 30 trace = 'on' 31 32 return """ 33 <html><body> 34 <p>Toggle tracebacks <a href="toggleTracebacks">%s</a></p> 35 <p><a href="/doesNotExist">Click me; I'm a broken link!</a></p> 36 <p> 37 <a href="/error?code=403"> 38 Use a custom error page from a file. 39 </a> 40 </p> 41 <p>These errors are explicitly raised by the application:</p> 42 <ul> 43 <li><a href="/error?code=400">400</a></li> 44 <li><a href="/error?code=401">401</a></li> 45 <li><a href="/error?code=402">402</a></li> 46 <li><a href="/error?code=500">500</a></li> 47 </ul> 48 <p><a href="/messageArg">You can also set the response body 49 when you raise an error.</a></p> 50 </body></html> 51 """ % trace
52 index.exposed = True 53
54 - def toggleTracebacks(self):
55 # simple function to toggle tracebacks on and off 56 tracebacks = cherrypy.request.show_tracebacks 57 cherrypy.config.update({'request.show_tracebacks': not tracebacks}) 58 59 # redirect back to the index 60 raise cherrypy.HTTPRedirect('/')
61 toggleTracebacks.exposed = True 62
63 - def error(self, code):
64 # raise an error based on the get query 65 raise cherrypy.HTTPError(status=code)
66 error.exposed = True 67
68 - def messageArg(self):
69 message = ("If you construct an HTTPError with a 'message' " 70 "argument, it wil be placed on the error page " 71 "(underneath the status line by default).") 72 raise cherrypy.HTTPError(500, message=message)
73 messageArg.exposed = True
74 75 76 import os.path 77 tutconf = os.path.join(os.path.dirname(__file__), 'tutorial.conf') 78 79 if __name__ == '__main__': 80 # CherryPy always starts with app.root when trying to map request URIs 81 # to objects, so we need to mount a request handler root. A request 82 # to '/' will be mapped to HelloWorld().index(). 83 cherrypy.quickstart(HTTPErrorDemo(), config=tutconf) 84 else: 85 # This branch is for the test suite; you can ignore it. 86 cherrypy.tree.mount(HTTPErrorDemo(), config=tutconf) 87