View Single Post
Old 10-13-2022, 08:48 AM   #53
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 12,471
Karma: 8025600
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
I added the ability to use custom python context classes. The change is in calibre source.

How to use:
  1. Create a subclass of utils.formatter.PythonTemplateContext. Add whatever you want to it.
  2. Pass an instance of your class to the formatter using
    Code:
    python_context_object=whatever
    as in
    Code:
    formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi,
                                      python_context_object=CustomContext())
  3. If you want something to happen when the object is used, override
    Code:
    set_values(**kwargs)
    This method is called just before executing the template, providing the known attributes db, globals, and arguments. Be sure to call the superclass method.
Here is an example test of the new feature:
Code:
        template = '''python:
def evaluate(book, ctx):
    tags = ctx.db.new_api.all_field_names('tags')
    return ','.join(list(ctx.helper_function(tags)))
'''
        from calibre.utils.formatter import PythonTemplateContext
        class CustomContext(PythonTemplateContext):
            def helper_function(self, arg):
                s = set(arg)
                s.add('helper called')
                return s

        v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi,
                                  python_context_object=CustomContext())
        self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two','helper called'})
chaley is offline   Reply With Quote