1 #!/usr/bin/env python 2 3 """ 4 Django adapter. 5 6 Copyright (C) 2006 Paul Boddie <paul@boddie.org.uk> 7 8 This library is free software; you can redistribute it and/or 9 modify it under the terms of the GNU Lesser General Public 10 License as published by the Free Software Foundation; either 11 version 2.1 of the License, or (at your option) any later version. 12 13 This library is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 Lesser General Public License for more details. 17 18 You should have received a copy of the GNU Lesser General Public 19 License along with this library; if not, write to the Free Software 20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 21 """ 22 23 import WebStack.Django 24 from WebStack.Generic import EndOfResponse 25 26 def deploy(resource, authenticator=None, address=None, handle_errors=1): 27 28 """ 29 Deploy the given 'resource', employing the optional 'authenticator' to 30 protect it. The optional 'handle_errors' parameter (if true) causes handlers 31 to deal with uncaught exceptions cleanly. 32 33 The optional 'address' parameter is deliberately ignored. 34 """ 35 36 def _deploy(request, *args, **kw): 37 return respond(request, resource, authenticator=authenticator, 38 virtual_path_info=kw.get("vp"), handle_errors=handle_errors) 39 return _deploy 40 41 def respond(request, resource, authenticator=None, virtual_path_info=None, handle_errors=1): 42 43 """ 44 Dispatch to the root application-specific 'resource'. Employ the optional 45 'authenticator' to control access to the resource. Define the optional 46 'virtual_path_info' as the path information considered to belong to the 47 given 'resource'. 48 49 The optional 'handle_errors' parameter (if true) causes handlers to deal 50 with uncaught exceptions cleanly. 51 """ 52 53 trans = WebStack.Django.Transaction(request) 54 if virtual_path_info: 55 trans.set_virtual_path_info(virtual_path_info) 56 57 try: 58 if authenticator is None or authenticator.authenticate(trans): 59 try: 60 resource.respond(trans) 61 except EndOfResponse: 62 pass 63 except Exception, exc: 64 if handle_errors: 65 trans.set_response_code(500) # Internal error 66 else: 67 raise 68 else: 69 trans.set_response_code(401) # Unauthorized 70 trans.set_header_value("WWW-Authenticate", '%s realm="%s"' % ( 71 authenticator.get_auth_type(), authenticator.get_realm())) 72 finally: 73 trans.commit() 74 return trans.response 75 76 # vim: tabstop=4 expandtab shiftwidth=4