pythonflask

How to make tuple type SQL results to be ready to display in Flask?


A typical query such as this:

conn=sql.connect('./database.db')
cursor=conn.cursor()
cursor.execute('SELECT year, unit, facilities, workforce, vehicles FROM units WHERE unit = ?', (unit,))
unit = cursor.fetchall()
conn.close()

works right to result whatever is needed from the database.

However when it comes to passing this "unit" variable to template page as it is in Flask as it is to iterate and display in a table with this ending in route;

return render_template('analysis.html', unit=unit)

I get an error:

TypeError: int() argument must be a string, a bytes-like object or a real number, not 'tuple'

I have tried to convert the whole thing to a list with this:

unit = list(unit)

The error has not changed.

Also I have tried to dump it as json with this;

unit = json.dumps(unit)

Flask returned this error:

ValueError: invalid literal for int() with base 10: '['

So I thought there should be some workaround to convert my multiline tuple result, to have it displayed, with this basic given database connection scheme. Your help is very much appreciated.


Solution

  • There was nothing special in the template file but the variable "unit" holding the datum, and a for loop to distribute it's elements to one html table.

    Here is how template looks like:

    
    <tbody>
    
        {% for element in unit %}
                            
        <tr>
        
            <td>{{ element[0] }} </td>
                            
            <td>{{ element[1] }}</td>
    
            <td>{{ element[2] }}</td>
                            
        </tr>
                            
        {% endfor %}
    
    </tbody>
    

    Thank you all, who are writing suggestions. I have found the solution to define an empty list such as unit_result, populating the list item with a loop and sending it to the template.

    
    #prepare for the table
    unit_result = []
    for i in range(len(unit)):
        unit_result.append((unit[i][0], unit[i][1], unit[i][2]))
        
    return render_template('analysis.html', unit_result=unit_result)
    

    The new template will include the following line instead of the older one:

    {% for element in unit_result %}