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