Ejemplo n.º 1
0
def render_template(request, template_path, context):
    """
    Render a template with context.

    Always inserts the request into the context, so you don't have to.
    Also stores the context if we're doing unit tests.  Helpful!
    """
    template = request.template_env.get_template(
        template_path)
    context['request'] = request
    rendered_csrf_token = render_csrf_form_token(request)
    if rendered_csrf_token is not None:
        context['csrf_token'] = render_csrf_form_token(request)

    # allow plugins to do things to the context
    if request.controller_name:
        context = hook_transform(
            (request.controller_name, template_path),
            context)

    # More evil: allow plugins to possibly do something to the context
    # in every request ever with access to the request and other
    # variables.  Note: this is slower than using
    # template_global_context
    context = hook_transform(
        'template_context_prerender', context)

    rendered = template.render(context)

    if common.TESTS_ENABLED:
        TEMPLATE_TEST_CONTEXT[template_path] = context

    return rendered
Ejemplo n.º 2
0
def render_template(request, template_path, context):
    """
    Render a template with context.

    Always inserts the request into the context, so you don't have to.
    Also stores the context if we're doing unit tests.  Helpful!
    """
    template = request.template_env.get_template(template_path)
    context['request'] = request
    rendered_csrf_token = render_csrf_form_token(request)
    if rendered_csrf_token is not None:
        context['csrf_token'] = render_csrf_form_token(request)

    # allow plugins to do things to the context
    if request.controller_name:
        context = hook_transform((request.controller_name, template_path),
                                 context)

    # More evil: allow plugins to possibly do something to the context
    # in every request ever with access to the request and other
    # variables.  Note: this is slower than using
    # template_global_context
    context = hook_transform('template_context_prerender', context)

    rendered = template.render(context)

    if common.TESTS_ENABLED:
        TEMPLATE_TEST_CONTEXT[template_path] = context

    return rendered
Ejemplo n.º 3
0
    def _finish_call_backend(self, request, environ, start_response):
        # Log user out if authentication_disabled
        no_auth_logout(request)

        request.controller_name = None
        try:
            found_rule, url_values = request.map_adapter.match(
                return_rule=True)
            request.matchdict = url_values
        except RequestRedirect as response:
            # Deal with 301 responses eg due to missing final slash
            return response(environ, start_response)
        except HTTPException as exc:
            # Stop and render exception
            return render_http_exception(request, exc,
                                         exc.get_description(environ))(
                                             environ, start_response)

        controller = endpoint_to_controller(found_rule)
        # Make a reference to the controller's symbolic name on the request...
        # used for lazy context modification
        request.controller_name = found_rule.endpoint

        ## TODO: get rid of meddleware, turn it into hooks only
        # pass the request through our meddleware classes
        try:
            for m in self.meddleware:
                response = m.process_request(request, controller)
                if response is not None:
                    return response(environ, start_response)
        except HTTPException as e:
            return render_http_exception(
                request, e, e.get_description(environ))(environ,
                                                        start_response)

        request = hook_transform("modify_request", request)

        request.start_response = start_response

        # get the Http response from the controller
        try:
            response = controller(request)
        except HTTPException as e:
            response = render_http_exception(request, e,
                                             e.get_description(environ))

        # pass the response through the meddlewares
        try:
            for m in self.meddleware[::-1]:
                m.process_response(request, response)
        except HTTPException as e:
            response = render_http_exception(request, e,
                                             e.get_description(environ))

        self.session_manager.save_session_to_cookie(request.session, request,
                                                    response)

        return response(environ, start_response)
Ejemplo n.º 4
0
    def _finish_call_backend(self, request, environ, start_response):
        # Log user out if authentication_disabled
        no_auth_logout(request)

        request.controller_name = None
        try:
            found_rule, url_values = request.map_adapter.match(return_rule=True)
            request.matchdict = url_values
        except RequestRedirect as response:
            # Deal with 301 responses eg due to missing final slash
            return response(environ, start_response)
        except HTTPException as exc:
            # Stop and render exception
            return render_http_exception(
                request, exc,
                exc.get_description(environ))(environ, start_response)

        controller = endpoint_to_controller(found_rule)
        # Make a reference to the controller's symbolic name on the request...
        # used for lazy context modification
        request.controller_name = found_rule.endpoint

        ## TODO: get rid of meddleware, turn it into hooks only
        # pass the request through our meddleware classes
        try:
            for m in self.meddleware:
                response = m.process_request(request, controller)
                if response is not None:
                    return response(environ, start_response)
        except HTTPException as e:
            return render_http_exception(
                request, e,
                e.get_description(environ))(environ, start_response)

        request = hook_transform("modify_request", request)

        request.start_response = start_response

        # get the Http response from the controller
        try:
            response = controller(request)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        # pass the response through the meddlewares
        try:
            for m in self.meddleware[::-1]:
                m.process_response(request, response)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        self.session_manager.save_session_to_cookie(
            request.session,
            request, response)

        return response(environ, start_response)
Ejemplo n.º 5
0
def test_hook_transform():
    """
    Test the hook_transform method
    """
    cfg = build_config(CONFIG_ALL_CALLABLES)

    mg_globals.app_config = cfg['mediagoblin']
    mg_globals.global_config = cfg

    setup_plugins()

    assert pluginapi.hook_transform("expand_tuple",
                                    (-1, 0)) == (-1, 0, 1, 2, 3)
Ejemplo n.º 6
0
def test_hook_transform():
    """
    Test the hook_transform method
    """
    cfg = build_config(CONFIG_ALL_CALLABLES)

    mg_globals.app_config = cfg['mediagoblin']
    mg_globals.global_config = cfg

    setup_plugins()

    assert pluginapi.hook_transform(
        "expand_tuple", (-1, 0)) == (-1, 0, 1, 2, 3)
Ejemplo n.º 7
0
def get_jinja_env(template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    set_thread_locale(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if locale in SETUP_JINJA_ENVS:
        return SETUP_JINJA_ENVS[locale]

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader,
        autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=["jinja2.ext.i18n", "jinja2.ext.autoescape", TemplateHookExtension],
    )

    template_env.install_gettext_callables(
        mg_globals.thread_scope.translations.ugettext, mg_globals.thread_scope.translations.ungettext
    )

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    template_env.globals["fetch_messages"] = messages.fetch_messages
    template_env.globals["app_config"] = mg_globals.app_config
    template_env.globals["global_config"] = mg_globals.global_config
    template_env.globals["version"] = _version.__version__
    template_env.globals["auth"] = mg_globals.app.auth

    template_env.filters["urlencode"] = url_quote_plus

    # add human readable fuzzy date time
    template_env.globals["timesince"] = timesince

    # allow for hooking up plugin templates
    template_env.globals["get_hook_templates"] = get_hook_templates

    template_env.globals = hook_transform("template_global_context", template_env.globals)

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
Ejemplo n.º 8
0
def paste_app_factory(global_config, **app_config):
    configs = app_config['config'].split()
    mediagoblin_config = None
    for config in configs:
        if os.path.exists(config) and os.access(config, os.R_OK):
            mediagoblin_config = config
            break

    if not mediagoblin_config:
        raise IOError("Usable mediagoblin config not found.")

    mgoblin_app = MediaGoblinApp(mediagoblin_config)
    mgoblin_app = hook_transform('wrap_wsgi', mgoblin_app)

    return mgoblin_app
Ejemplo n.º 9
0
def media_home(request, media, page, **kwargs):
    """
    'Homepage' of a MediaEntry()
    """
    comment_id = request.matchdict.get('comment', None)
    if comment_id:
        if request.user:
            mark_comment_notification_seen(comment_id, request.user)

        pagination = Pagination(
            page, media.get_comments(
                mg_globals.app_config['comments_ascending']),
            MEDIA_COMMENTS_PER_PAGE,
            comment_id)
    else:
        pagination = Pagination(
            page, media.get_comments(
                mg_globals.app_config['comments_ascending']),
            MEDIA_COMMENTS_PER_PAGE)

    comments = pagination()

    comment_form = user_forms.MediaCommentForm(request.form)

    media_template_name = media.media_manager.display_template

    context = {
        'media': media,
        'comments': comments,
        'pagination': pagination,
        'comment_form': comment_form,
        'app_config': mg_globals.app_config}

    # Since the media template name gets swapped out for each media
    # type, normal context hooks don't work if you want to affect all
    # media displays.  This gives a general purpose hook.
    context = hook_transform(
        "media_home_context", context)

    return render_to_response(
        request,
        media_template_name,
        context)
Ejemplo n.º 10
0
def media_home(request, media, page, **kwargs):
    """
    'Homepage' of a MediaEntry()
    """
    comment_id = request.matchdict.get('comment', None)
    if comment_id:
        if request.user:
            mark_comment_notification_seen(comment_id, request.user)

        pagination = Pagination(
            page, media.get_comments(
                mg_globals.app_config['comments_ascending']),
            MEDIA_COMMENTS_PER_PAGE,
            comment_id)
    else:
        pagination = Pagination(
            page, media.get_comments(
                mg_globals.app_config['comments_ascending']),
            MEDIA_COMMENTS_PER_PAGE)

    comments = pagination()

    comment_form = user_forms.MediaCommentForm(request.form)

    media_template_name = media.media_manager.display_template

    context = {
        'media': media,
        'comments': comments,
        'pagination': pagination,
        'comment_form': comment_form,
        'app_config': mg_globals.app_config}

    # Since the media template name gets swapped out for each media
    # type, normal context hooks don't work if you want to affect all
    # media displays.  This gives a general purpose hook.
    context = hook_transform(
        "media_home_context", context)

    return render_to_response(
        request,
        media_template_name,
        context)
Ejemplo n.º 11
0
    def call_backend(self, environ, start_response):
        request = Request(environ)

        # Compatibility with django, use request.args preferrably
        request.GET = request.args

        ## Routing / controller loading stuff
        map_adapter = self.url_map.bind_to_environ(request.environ)

        # By using fcgi, mediagoblin can run under a base path
        # like /mediagoblin/. request.path_info contains the
        # path inside mediagoblin. If the something needs the
        # full path of the current page, that should include
        # the basepath.
        # Note: urlgen and routes are fine!
        request.full_path = environ["SCRIPT_NAME"] + request.path
        # python-routes uses SCRIPT_NAME. So let's use that too.
        # The other option would be:
        # request.full_path = environ["SCRIPT_URL"]

        # Fix up environ for urlgen
        # See bug: https://bitbucket.org/bbangert/routes/issue/55/cache_hostinfo-breaks-on-https-off
        if environ.get('HTTPS', '').lower() == 'off':
            environ.pop('HTTPS')

        ## Attach utilities to the request object
        # Do we really want to load this via middleware?  Maybe?
        session_manager = self.session_manager
        request.session = session_manager.load_session_from_cookie(request)
        # Attach self as request.app
        # Also attach a few utilities from request.app for convenience?
        request.app = self

        request.db = self.db
        request.staticdirect = self.staticdirector

        request.locale = translate.get_locale_from_request(request)
        request.template_env = template.get_jinja_env(
            self.template_loader, request.locale)

        def build_proxy(endpoint, **kw):
            try:
                qualified = kw.pop('qualified')
            except KeyError:
                qualified = False

            return map_adapter.build(
                    endpoint,
                    values=dict(**kw),
                    force_external=qualified)

        request.urlgen = build_proxy

        # Log user out if authentication_disabled
        no_auth_logout(request)

        mg_request.setup_user_in_request(request)

        request.controller_name = None
        try:
            found_rule, url_values = map_adapter.match(return_rule=True)
            request.matchdict = url_values
        except RequestRedirect as response:
            # Deal with 301 responses eg due to missing final slash
            return response(environ, start_response)
        except HTTPException as exc:
            # Stop and render exception
            return render_http_exception(
                request, exc,
                exc.get_description(environ))(environ, start_response)

        controller = endpoint_to_controller(found_rule)
        # Make a reference to the controller's symbolic name on the request...
        # used for lazy context modification
        request.controller_name = found_rule.endpoint

        # pass the request through our meddleware classes
        try:
            for m in self.meddleware:
                response = m.process_request(request, controller)
                if response is not None:
                    return response(environ, start_response)
        except HTTPException as e:
            return render_http_exception(
                request, e,
                e.get_description(environ))(environ, start_response)

        request = hook_transform("modify_request", request)

        request.start_response = start_response

        # get the Http response from the controller
        try:
            response = controller(request)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        # pass the response through the meddlewares
        try:
            for m in self.meddleware[::-1]:
                m.process_response(request, response)
        except HTTPException as e:
            response = render_http_exception(
                request, e, e.get_description(environ))

        session_manager.save_session_to_cookie(request.session,
                                               request, response)

        return response(environ, start_response)
Ejemplo n.º 12
0
def get_jinja_env(template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    set_thread_locale(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if locale in SETUP_JINJA_ENVS:
        return SETUP_JINJA_ENVS[locale]

    # The default config does not require a [jinja2] block.
    # You may create one if you wish to enable additional jinja2 extensions,
    # see example in config_spec.ini
    jinja2_config = mg_globals.global_config.get('jinja2', {})
    local_exts = jinja2_config.get('extensions', [])

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader,
        autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=[
            'jinja2.ext.i18n', 'jinja2.ext.autoescape', TemplateHookExtension
        ] + local_exts)

    template_env.install_gettext_callables(
        mg_globals.thread_scope.translations.ugettext,
        mg_globals.thread_scope.translations.ungettext)

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    template_env.globals['fetch_messages'] = messages.fetch_messages
    template_env.globals['app_config'] = mg_globals.app_config
    template_env.globals['global_config'] = mg_globals.global_config
    template_env.globals['version'] = _version.__version__
    template_env.globals['auth'] = mg_globals.app.auth

    template_env.filters['urlencode'] = url_quote_plus

    # add human readable fuzzy date time
    template_env.globals['timesince'] = timesince

    # allow for hooking up plugin templates
    template_env.globals['get_hook_templates'] = get_hook_templates

    template_env.globals = hook_transform('template_global_context',
                                          template_env.globals)

    #### THIS IS TEMPORARY, PLEASE FIX IT
    ## Notifications stuff is not yet a plugin (and we're not sure it will be),
    ## but it needs to add stuff to the context.  This is THE WRONG WAY TO DO IT
    from mediagoblin import notifications
    template_env.globals['get_notifications'] = notifications.get_notifications
    template_env.globals[
        'get_notification_count'] = notifications.get_notification_count
    template_env.globals[
        'get_comment_subscription'] = notifications.get_comment_subscription

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env
Ejemplo n.º 13
0
def get_jinja_env(app, template_loader, locale):
    """
    Set up the Jinja environment,

    (In the future we may have another system for providing theming;
    for now this is good enough.)
    """
    set_thread_locale(locale)

    # If we have a jinja environment set up with this locale, just
    # return that one.
    if locale in SETUP_JINJA_ENVS:
        return SETUP_JINJA_ENVS[locale]

    # The default config does not require a [jinja2] block.
    # You may create one if you wish to enable additional jinja2 extensions,
    # see example in config_spec.ini 
    jinja2_config = app.global_config.get('jinja2', {})
    local_exts = jinja2_config.get('extensions', [])

    # jinja2.StrictUndefined will give exceptions on references
    # to undefined/unknown variables in templates.
    template_env = jinja2.Environment(
        loader=template_loader, autoescape=True,
        undefined=jinja2.StrictUndefined,
        extensions=[
            'jinja2.ext.i18n', 'jinja2.ext.autoescape',
            TemplateHookExtension] + local_exts)

    if six.PY2:
        template_env.install_gettext_callables(mg_globals.thread_scope.translations.ugettext,
                                           mg_globals.thread_scope.translations.ungettext)
    else:
        template_env.install_gettext_callables(mg_globals.thread_scope.translations.gettext,
                                           mg_globals.thread_scope.translations.ngettext)

    # All templates will know how to ...
    # ... fetch all waiting messages and remove them from the queue
    # ... construct a grid of thumbnails or other media
    # ... have access to the global and app config
    # ... determine if the language is rtl or ltr
    template_env.globals['fetch_messages'] = messages.fetch_messages
    template_env.globals['app_config'] = app.app_config
    template_env.globals['global_config'] = app.global_config
    template_env.globals['version'] = _version.__version__
    template_env.globals['auth'] = app.auth
    template_env.globals['is_rtl'] = is_rtl(locale)
    template_env.filters['urlencode'] = url_quote_plus

    # add human readable fuzzy date time
    template_env.globals['timesince'] = timesince

    # allow for hooking up plugin templates
    template_env.globals['get_hook_templates'] = get_hook_templates

    template_env.globals = hook_transform(
        'template_global_context', template_env.globals)

    #### THIS IS TEMPORARY, PLEASE FIX IT
    ## Notifications stuff is not yet a plugin (and we're not sure it will be),
    ## but it needs to add stuff to the context.  This is THE WRONG WAY TO DO IT
    from mediagoblin import notifications
    template_env.globals['get_notifications'] = notifications.get_notifications
    template_env.globals[
        'get_notification_count'] = notifications.get_notification_count
    template_env.globals[
        'get_comment_subscription'] = notifications.get_comment_subscription

    if exists(locale):
        SETUP_JINJA_ENVS[locale] = template_env

    return template_env