~homeworkprod/byceps

ddd33bd2f9170e5d4a39b802147620b579172f2d — Jochen Kupperschmidt 5 days ago d806399
Remove functionality to render snippet as page

This is superceded by pages, but also doesn't work anymore since pages
have been introduced.
5 files changed, 6 insertions(+), 133 deletions(-)

D byceps/blueprints/site/snippet/templates/site/snippet/error.html
D byceps/blueprints/site/snippet/templates/site/snippet/view.html
M byceps/blueprints/site/snippet/templating.py
M byceps/blueprints/site/snippet/views.py
M byceps/services/snippet/mountpoint_service.py
D byceps/blueprints/site/snippet/templates/site/snippet/error.html => byceps/blueprints/site/snippet/templates/site/snippet/error.html +0 -11
@@ 1,11 0,0 @@
{% extends 'layout/base.html' %}
{% from 'macros/misc.html' import render_notification %}
{% set page_title = _('Error') %}

{% block body %}

  <h1>{{ page_title }}</h1>

{{ render_notification(_('Sorry, an error has occurred.'), category='danger', icon='warning') }}

{%- endblock %}

D byceps/blueprints/site/snippet/templates/site/snippet/view.html => byceps/blueprints/site/snippet/templates/site/snippet/view.html +0 -15
@@ 1,15 0,0 @@
{% extends 'layout/base.html' %}

{% block head %}
  {%- if head %}
{{ head|safe }}
  {%- endif -%}
{% endblock %}

{% block body %}

  <h1>{{ page_title }}</h1>

{{ body|safe }}

{%- endblock %}

M byceps/blueprints/site/snippet/templating.py => byceps/blueprints/site/snippet/templating.py +5 -64
@@ 7,43 7,21 @@ byceps.blueprints.site.snippet.templating
"""

from __future__ import annotations
import sys
import traceback
from typing import Any, Dict, Optional, Union
from typing import Any, Dict, Optional

from flask import abort, g, render_template, url_for
from jinja2 import Template, TemplateNotFound
from flask import g
from jinja2 import Template

from ....services.snippet.dbmodels.snippet import SnippetVersion
from ....services.snippet import mountpoint_service, service as snippet_service
from ....services.snippet import service as snippet_service
from ....services.snippet.service import SnippetNotFound
from ....services.snippet.transfer.models import Mountpoint, Scope
from ....services.snippet.transfer.models import Scope
from ....util.templating import get_variable_value, load_template


Context = Dict[str, Any]


def render_snippet_as_page(
    version: SnippetVersion,
) -> Union[str, tuple[str, int]]:
    """Render the given version of the snippet, or an error page if
    that fails.
    """
    try:
        context = get_snippet_context(version)
        return render_template('site/snippet/view.html', **context)
    except TemplateNotFound:
        abort(404)
    except Exception as e:
        print('Error in snippet markup:', e, file=sys.stderr)
        traceback.print_exc()
        context = {
            'message': str(e),
        }
        return render_template('site/snippet/error.html', **context), 500


def get_snippet_context(version: SnippetVersion) -> Context:
    """Return the snippet context to insert into the outer template."""
    template = _load_template_with_globals(version.body)


@@ 129,40 107,3 @@ def _load_template_with_globals(source: str) -> Template:
    }

    return load_template(source, template_globals=template_globals)


def url_for_snippet(endpoint_suffix: str, **kwargs) -> str:
    """Render an URL pointing to the snippet document's mountpoint."""
    mountpoints = _get_mountpoints()

    # Endpoint suffix is unique per site.
    mountpoints_by_endpoint_suffix = {
        mp.endpoint_suffix: mp for mp in mountpoints
    }

    mountpoint = mountpoints_by_endpoint_suffix[endpoint_suffix]

    return url_for(f'snippet.view', url_path=mountpoint.url_path, **kwargs)


def _get_mountpoints() -> set[Mountpoint]:
    """Return site-specific mountpoints.

    Preferrably from request-local cache, if available. From the
    database if not yet cached.
    """
    site_id = getattr(g, 'site_id', None)
    if site_id is None:
        return set()

    request_context_key = f'snippet_mountpoints_{site_id}'

    mountpoints_from_request_context = g.get(request_context_key)
    if mountpoints_from_request_context:
        return mountpoints_from_request_context
    else:
        mountpoints_from_database = mountpoint_service.get_mountpoints_for_site(
            site_id
        )
        setattr(g, request_context_key, mountpoints_from_database)
        return mountpoints_from_database

M byceps/blueprints/site/snippet/views.py => byceps/blueprints/site/snippet/views.py +1 -26
@@ 6,16 6,9 @@ byceps.blueprints.site.snippet.views
:License: Revised BSD (see `LICENSE` file for details)
"""

from flask import abort, g

from ....services.snippet import mountpoint_service
from ....util.framework.blueprint import create_blueprint

from .templating import (
    render_snippet_as_page,
    render_snippet_as_partial_from_template,
    url_for_snippet,
)
from .templating import render_snippet_as_partial_from_template


blueprint = create_blueprint('snippet', __name__)


@@ 23,21 16,3 @@ blueprint = create_blueprint('snippet', __name__)
blueprint.add_app_template_global(
    render_snippet_as_partial_from_template, 'render_snippet'
)
blueprint.add_app_template_global(url_for_snippet)


@blueprint.get('/<path:url_path>')
def view(url_path):
    """Show the current version of the snippet that is mounted for the
    current site at the given URL path.
    """
    url_path = '/' + url_path

    version = mountpoint_service.find_current_snippet_version_for_url_path(
        g.site_id, url_path
    )

    if version is None:
        abort(404)

    return render_snippet_as_page(version)

M byceps/services/snippet/mountpoint_service.py => byceps/services/snippet/mountpoint_service.py +0 -17
@@ 14,7 14,6 @@ from ...database import db
from ..site.transfer.models import SiteID

from .dbmodels.mountpoint import Mountpoint as DbMountpoint
from .dbmodels.snippet import CurrentVersionAssociation, Snippet, SnippetVersion
from .transfer.models import Mountpoint, MountpointID, SnippetID




@@ 61,22 60,6 @@ def get_mountpoints_for_site(site_id: SiteID) -> set[Mountpoint]:
    return {_db_entity_to_mountpoint(mp) for mp in mountpoints}


def find_current_snippet_version_for_url_path(
    site_id: SiteID, url_path: str
) -> SnippetVersion:
    """Return the current version of the snippet mounted at that URL
    path for that site, or `None` if not found.
    """
    return db.session \
        .query(SnippetVersion) \
        .join(CurrentVersionAssociation) \
        .join(Snippet) \
        .join(DbMountpoint) \
        .filter(DbMountpoint.site_id == site_id) \
        .filter(DbMountpoint.url_path == url_path) \
        .one_or_none()


def _db_entity_to_mountpoint(entity: DbMountpoint) -> Mountpoint:
    return Mountpoint(
        entity.id,