'Import error for templated queries in Python using JinjaSql

So, I'm trying to create SQL templates with certain parameters would change based on the call. I reviewed many other methods but I found the method using JinjaSql more suitable and readable for the requirement of my module.

I tried creating a class as below (code shortened) to create a templated list of queries.

from jinjasql import JinjaSql
j = JinjaSql(param_style='pyformat')


class QueryTemplate(object):
    def highest_pp_team_score(self, tour_name, year):
        params = {'tour_name': [], 'year': []}

        params['tour_name'].append(tour_name)
        params['year'].append(year)

        template = """
            SELECT 
              id.match_id,
              id.inning,
              id.team
            FROM 
              innings_deliveries as id
            WHERE 
              id.name LIKE {{ tour_name }}
              AND YEAR(id.start_date) = {{ year }} 
            """
        query, bind_params = j.prepare_query(template, params)
        return query % bind_params

... when I try and run, I get the below error. It's on the import itself.

ImportError: cannot import name 'Markup' from 'jinja2.utils'

After reading about the issue, I couldn't find any resolutions to my case but I did find a thread with similar issue. It needed me to add few lines to the import. Since, the original issue was related to flask, I couldn't implement it to my case.



Solution 1:[1]

This is an issue in the library you are using. It has been reported on their issue tracker already, see https://github.com/sripathikrishnan/jinjasql/issues/50

What you could do is to downgrade your Jinja version to the one before 3.1.0 that brought those breaking changes of removing Markup and escape.


If you do have a requirements.txt file to install your dependencies, this is as simple as adding a line in it like

jinja2<3.1.0

And redo a

pip install --requirements requirements.txt

If you don't have such a file but are installing your packages with pip, you could do

pip install --upgrade 'jinja2<3.1.0'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1