3
0
Fork 0
wuttaweb/src/wuttaweb/views/base.py
Lance Edgar 7766ca6b12 fix: add notfound() View method; auto-append trailing slash
the latter provides auto-redirect to `/widgets/` when user visits
`/widgets` for example
2024-08-05 21:58:31 -05:00

99 lines
2.9 KiB
Python

# -*- coding: utf-8; -*-
################################################################################
#
# wuttaweb -- Web App for Wutta Framework
# Copyright © 2024 Lance Edgar
#
# This file is part of Wutta Framework.
#
# Wutta Framework is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# Wutta Framework is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# Wutta Framework. If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
Base Logic for Views
"""
from pyramid import httpexceptions
from wuttaweb import forms
class View:
"""
Base class for all class-based views.
Instances of this class (or rather, a subclass) are created by
Pyramid when processing a request. They will have the following
attributes:
.. attribute:: request
Reference to the current :term:`request` object.
.. attribute:: app
Reference to the :term:`app handler`.
.. attribute:: config
Reference to the app :term:`config object`.
"""
def __init__(self, request, context=None):
self.request = request
self.config = self.request.wutta_config
self.app = self.config.get_app()
def forbidden(self):
"""
Convenience method, to raise a HTTP 403 Forbidden exception::
raise self.forbidden()
"""
return httpexceptions.HTTPForbidden()
def make_form(self, **kwargs):
"""
Make and return a new :class:`~wuttaweb.forms.base.Form`
instance, per the given ``kwargs``.
This is the "default" form factory which merely invokes
the constructor.
"""
return forms.Form(self.request, **kwargs)
def notfound(self):
"""
Convenience method, to raise a HTTP 404 Not Found exception::
raise self.notfound()
"""
return httpexceptions.HTTPNotFound()
def redirect(self, url, **kwargs):
"""
Convenience method to return a HTTP 302 response.
Note that this technically returns an "exception" - so in
your code, you can either return that error, or raise it::
return self.redirect('/')
# ..or
raise self.redirect('/')
Which you should do will depend on context, but raising the
error is always "safe" since Pyramid will handle that
correctly no matter what.
"""
return httpexceptions.HTTPFound(location=url, **kwargs)