feat: begin integrating WuttaWeb as upstream dependency

the bare minimum, just to get the relationship established.  mostly
it's calling upstream subscriber / event hooks where applicable.

this also overhauls the docs config to use furo theme etc.
This commit is contained in:
Lance Edgar 2024-07-12 09:35:34 -05:00
parent e531f98079
commit ce156d6278
6 changed files with 112 additions and 318 deletions

View file

@ -3,5 +3,4 @@
======================== ========================
.. automodule:: tailbone.subscribers .. automodule:: tailbone.subscribers
:members:
.. autofunction:: new_request

View file

@ -1,38 +1,21 @@
# -*- coding: utf-8; -*- # Configuration file for the Sphinx documentation builder.
# #
# Tailbone documentation build configuration file, created by # For the full list of built-in configuration values, see the documentation:
# sphinx-quickstart on Sat Feb 15 23:15:27 2014. # https://www.sphinx-doc.org/en/master/usage/configuration.html
#
# This file is exec()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys # -- Project information -----------------------------------------------------
import os # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import sphinx_rtd_theme from importlib.metadata import version as get_version
exec(open(os.path.join(os.pardir, 'tailbone', '_version.py')).read()) project = 'Tailbone'
copyright = '2010 - 2024, Lance Edgar'
author = 'Lance Edgar'
release = get_version('Tailbone')
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [ extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.autodoc',
'sphinx.ext.todo', 'sphinx.ext.todo',
@ -40,241 +23,30 @@ extensions = [
'sphinx.ext.viewcode', 'sphinx.ext.viewcode',
] ]
templates_path = ['_templates']
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
intersphinx_mapping = { intersphinx_mapping = {
'rattail': ('https://rattailproject.org/docs/rattail/', None), 'rattail': ('https://rattailproject.org/docs/rattail/', None),
'webhelpers2': ('https://webhelpers2.readthedocs.io/en/latest/', None), 'webhelpers2': ('https://webhelpers2.readthedocs.io/en/latest/', None),
'wuttaweb': ('https://rattailproject.org/docs/wuttaweb/', None),
'wuttjamaican': ('https://rattailproject.org/docs/wuttjamaican/', None),
} }
# Add any paths that contain templates here, relative to this directory. # allow todo entries to show up
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Tailbone'
copyright = u'2010 - 2020, Lance Edgar'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# version = '0.3'
version = '.'.join(__version__.split('.')[:2])
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# Allow todo entries to show up.
todo_include_todos = True todo_include_todos = True
# -- Options for HTML output ---------------------------------------------- # -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
# The theme to use for HTML and HTML Help pages. See the documentation for html_theme = 'furo'
# a list of builtin themes. html_static_path = ['_static']
# html_theme = 'classic'
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top # The name of an image file (relative to this directory) to place at the top
# of the sidebar. # of the sidebar.
#html_logo = None #html_logo = None
html_logo = 'images/rattail_avatar.png' #html_logo = 'images/rattail_avatar.png'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'Tailbonedoc' #htmlhelp_basename = 'Tailbonedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'Tailbone.tex', u'Tailbone Documentation',
u'Lance Edgar', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'tailbone', u'Tailbone Documentation',
[u'Lance Edgar'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Tailbone', u'Tailbone Documentation',
u'Lance Edgar', 'Tailbone', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False

View file

@ -59,12 +59,13 @@ dependencies = [
"transaction", "transaction",
"waitress", "waitress",
"WebHelpers2", "WebHelpers2",
"WuttaWeb",
"zope.sqlalchemy>=1.5", "zope.sqlalchemy>=1.5",
] ]
[project.optional-dependencies] [project.optional-dependencies]
docs = ["Sphinx", "sphinx-rtd-theme"] docs = ["Sphinx", "furo"]
tests = ["coverage", "mock", "pytest", "pytest-cov"] tests = ["coverage", "mock", "pytest", "pytest-cov"]

View file

@ -30,7 +30,9 @@ import warnings
import sqlalchemy as sa import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.orm import sessionmaker, scoped_session
from rattail.config import make_config, parse_list from wuttjamaican.util import parse_list
from rattail.config import make_config
from rattail.exceptions import ConfigurationError from rattail.exceptions import ConfigurationError
from rattail.db.types import GPCType from rattail.db.types import GPCType
@ -61,6 +63,9 @@ def make_rattail_config(settings):
rattail_config = make_config(path) rattail_config = make_config(path)
settings['rattail_config'] = rattail_config settings['rattail_config'] = rattail_config
# nb. this is for compaibility with wuttaweb
settings['wutta_config'] = rattail_config
# configure database sessions # configure database sessions
if hasattr(rattail_config, 'rattail_engine'): if hasattr(rattail_config, 'rattail_engine'):
tailbone.db.Session.configure(bind=rattail_config.rattail_engine) tailbone.db.Session.configure(bind=rattail_config.rattail_engine)

View file

@ -52,6 +52,9 @@ class ConfigExtension(BaseExtension):
config.setdefault('tailbone', 'themes.keys', 'default, butterball') config.setdefault('tailbone', 'themes.keys', 'default, butterball')
config.setdefault('tailbone', 'themes.expose_picker', 'true') config.setdefault('tailbone', 'themes.expose_picker', 'true')
# override oruga detection
config.setdefault('wuttaweb.oruga_detector.spec', 'tailbone.util:should_use_oruga')
def csrf_token_name(config): def csrf_token_name(config):
return config.get('tailbone', 'csrf_token_name', default='_csrf') return config.get('tailbone', 'csrf_token_name', default='_csrf')

View file

@ -24,7 +24,6 @@
Event Subscribers Event Subscribers
""" """
import json
import datetime import datetime
import logging import logging
import warnings import warnings
@ -37,13 +36,14 @@ import deform
from pyramid import threadlocal from pyramid import threadlocal
from webhelpers2.html import tags from webhelpers2.html import tags
from wuttaweb import subscribers as base
import tailbone import tailbone
from tailbone import helpers from tailbone import helpers
from tailbone.db import Session from tailbone.db import Session
from tailbone.config import csrf_header_name, should_expose_websockets from tailbone.config import csrf_header_name, should_expose_websockets
from tailbone.menus import make_simple_menus from tailbone.menus import make_simple_menus
from tailbone.util import (get_available_themes, get_global_search_options, from tailbone.util import get_available_themes, get_global_search_options
should_use_oruga)
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -51,42 +51,59 @@ log = logging.getLogger(__name__)
def new_request(event): def new_request(event):
""" """
Identify the current user, and cache their current permissions. Also adds Event hook called when processing a new request.
the ``rattail_config`` attribute to the request.
A global Rattail ``config`` should already be present within the Pyramid This first invokes the upstream hook:
application registry's settings, which would normally be accessed via:: :func:`wuttaweb:wuttaweb.subscribers.new_request()`
request.registry.settings['rattail_config'] It then adds more things to the request object; among them:
This function merely "promotes" that config object so that it is more .. attribute:: request.rattail_config
directly accessible, a la::
request.rattail_config Reference to the app :term:`config object`. Note that this
will be the same as ``request.wutta_config``.
.. note:: .. attribute:: request.user
This of course assumes that a Rattail ``config`` object *has* in fact
already been placed in the application registry settings. If this is
not the case, this function will do nothing.
Also, attach some goodies to the request object: Reference to the current authenticated user, or ``None``.
* The currently logged-in user instance (if any), as ``user``. .. attribute:: request.is_admin
* ``is_admin`` flag indicating whether user has the Administrator role. Flag indicating whether current user is a member of the
Administrator role.
* ``is_root`` flag indicating whether user is currently elevated to root. .. attribute:: request.is_root
* A shortcut method for permission checking, as ``has_perm()``. Flag indicating whether user is currently elevated to root
privileges. This is only possible if ``request.is_admin =
True``.
.. method:: request.has_perm(name)
Function to check if current user has the given permission.
.. method:: request.has_any_perm(*names)
Function to check if current user has any of the given
permissions.
.. method:: request.register_component(tagname, classname)
Function to register a Vue component for use with the app.
This can be called from wherever a component is defined, and
then in the base template all registered components will be
properly loaded.
""" """
log.debug("new request: %s", event) # log.debug("new request: %s", event)
request = event.request request = event.request
rattail_config = request.registry.settings.get('rattail_config')
# TODO: why would this ever be null? # invoke upstream logic
if rattail_config: base.new_request(event)
# compatibility
rattail_config = request.wutta_config
request.rattail_config = rattail_config request.rattail_config = rattail_config
else:
log.error("registry has no rattail_config ?!")
def user(request): def user(request):
user = None user = None
@ -101,15 +118,6 @@ def new_request(event):
request.set_property(user, reify=True) request.set_property(user, reify=True)
# nb. only add oruga check for "classic" web app
classic = rattail_config.parse_bool(request.registry.settings.get('tailbone.classic'))
if classic:
def use_oruga(request):
return should_use_oruga(request)
request.set_property(use_oruga, reify=True)
# assign client IP address to the session, for sake of versioning # assign client IP address to the session, for sake of versioning
Session().continuum_remote_addr = request.client_addr Session().continuum_remote_addr = request.client_addr
@ -161,27 +169,34 @@ def before_render(event):
""" """
Adds goodies to the global template renderer context. Adds goodies to the global template renderer context.
""" """
log.debug("before_render: %s", event) # log.debug("before_render: %s", event)
# invoke upstream logic
base.before_render(event)
request = event.get('request') or threadlocal.get_current_request() request = event.get('request') or threadlocal.get_current_request()
rattail_config = request.rattail_config config = request.wutta_config
app = rattail_config.get_app() app = config.get_app()
renderer_globals = event renderer_globals = event
renderer_globals['rattail_app'] = app
renderer_globals['app_title'] = app.get_title() # wuttaweb overrides
renderer_globals['app_version'] = app.get_version()
renderer_globals['h'] = helpers renderer_globals['h'] = helpers
renderer_globals['url'] = request.route_url
renderer_globals['rattail'] = rattail # misc.
renderer_globals['tailbone'] = tailbone
renderer_globals['model'] = app.model
renderer_globals['enum'] = request.rattail_config.get_enum()
renderer_globals['json'] = json
renderer_globals['datetime'] = datetime renderer_globals['datetime'] = datetime
renderer_globals['colander'] = colander renderer_globals['colander'] = colander
renderer_globals['deform'] = deform renderer_globals['deform'] = deform
renderer_globals['csrf_header_name'] = csrf_header_name(request.rattail_config) renderer_globals['csrf_header_name'] = csrf_header_name(config)
# TODO: deprecate / remove these
renderer_globals['rattail_app'] = app
renderer_globals['app_title'] = app.get_title()
renderer_globals['app_version'] = app.get_version()
renderer_globals['rattail'] = rattail
renderer_globals['tailbone'] = tailbone
renderer_globals['model'] = app.model
renderer_globals['enum'] = app.enum
# theme - we only want do this for classic web app, *not* API # theme - we only want do this for classic web app, *not* API
# TODO: so, clearly we need a better way to distinguish the two # TODO: so, clearly we need a better way to distinguish the two
@ -189,13 +204,13 @@ def before_render(event):
renderer_globals['b'] = 'o' if request.use_oruga else 'b' # for buefy renderer_globals['b'] = 'o' if request.use_oruga else 'b' # for buefy
renderer_globals['theme'] = request.registry.settings['tailbone.theme'] renderer_globals['theme'] = request.registry.settings['tailbone.theme']
# note, this is just a global flag; user still needs permission to see picker # note, this is just a global flag; user still needs permission to see picker
expose_picker = request.rattail_config.getbool('tailbone', 'themes.expose_picker', expose_picker = config.get_bool('tailbone.themes.expose_picker',
default=False) default=False)
renderer_globals['expose_theme_picker'] = expose_picker renderer_globals['expose_theme_picker'] = expose_picker
if expose_picker: if expose_picker:
# TODO: should remove 'falafel' option altogether # TODO: should remove 'falafel' option altogether
available = get_available_themes(request.rattail_config) available = get_available_themes(config)
options = [tags.Option(theme, value=theme) for theme in available] options = [tags.Option(theme, value=theme) for theme in available]
renderer_globals['theme_picker_options'] = options renderer_globals['theme_picker_options'] = options
@ -204,26 +219,25 @@ def before_render(event):
# (we don't want this to happen for the API either!) # (we don't want this to happen for the API either!)
# TODO: just..awful *shrug* # TODO: just..awful *shrug*
# note that we assume "simple" menus nowadays # note that we assume "simple" menus nowadays
if request.rattail_config.getbool('tailbone', 'menus.simple', default=True): if config.get_bool('tailbone.menus.simple', default=True):
renderer_globals['menus'] = make_simple_menus(request) renderer_globals['menus'] = make_simple_menus(request)
# TODO: ugh, same deal here # TODO: ugh, same deal here
renderer_globals['messaging_enabled'] = request.rattail_config.getbool( renderer_globals['messaging_enabled'] = config.get_bool('tailbone.messaging.enabled',
'tailbone', 'messaging.enabled', default=False) default=False)
# background color may be set per-request, by some apps # background color may be set per-request, by some apps
if hasattr(request, 'background_color') and request.background_color: if hasattr(request, 'background_color') and request.background_color:
renderer_globals['background_color'] = request.background_color renderer_globals['background_color'] = request.background_color
else: # otherwise we use the one from config else: # otherwise we use the one from config
renderer_globals['background_color'] = request.rattail_config.get( renderer_globals['background_color'] = config.get('tailbone.background_color')
'tailbone', 'background_color')
# maybe set custom stylesheet # maybe set custom stylesheet
css = None css = None
if request.user: if request.user:
css = rattail_config.get(f'tailbone.{request.user.uuid}', 'user_css') css = config.get(f'tailbone.{request.user.uuid}', 'user_css')
if not css: if not css:
css = rattail_config.get(f'tailbone.{request.user.uuid}', 'buefy_css') css = config.get(f'tailbone.{request.user.uuid}', 'buefy_css')
if css: if css:
warnings.warn(f"setting 'tailbone.{request.user.uuid}.buefy_css' should be" warnings.warn(f"setting 'tailbone.{request.user.uuid}.buefy_css' should be"
f"changed to 'tailbone.{request.user.uuid}.user_css'", f"changed to 'tailbone.{request.user.uuid}.user_css'",
@ -234,7 +248,7 @@ def before_render(event):
renderer_globals['global_search_data'] = get_global_search_options(request) renderer_globals['global_search_data'] = get_global_search_options(request)
# here we globally declare widths for grid filter pseudo-columns # here we globally declare widths for grid filter pseudo-columns
widths = request.rattail_config.get('tailbone', 'grids.filters.column_widths') widths = config.get('tailbone.grids.filters.column_widths')
if widths: if widths:
widths = widths.split(';') widths = widths.split(';')
if len(widths) < 2: if len(widths) < 2:
@ -245,7 +259,7 @@ def before_render(event):
renderer_globals['filter_verb_width'] = widths[1] renderer_globals['filter_verb_width'] = widths[1]
# declare global support for websockets, or lack thereof # declare global support for websockets, or lack thereof
renderer_globals['expose_websockets'] = should_expose_websockets(rattail_config) renderer_globals['expose_websockets'] = should_expose_websockets(config)
def add_inbox_count(event): def add_inbox_count(event):