librelist archives

« back to archive

Re: [flask] flask utf-8 postgresql 9.1 database UnicodeDecodeError [Solved]

Re: [flask] flask utf-8 postgresql 9.1 database UnicodeDecodeError [Solved]

From:
Igor TAmara
Date:
2012-06-02 @ 16:07
2012/6/2 Audrius Ka┼żukauskas <audrius@neutrino.lt>

> On Sat, 2012-06-02 at 09:12:50 -0500, Igor TAmara wrote:
> >  Hi, I'm starting with Flask and I got the exception :
> >
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1:
> > ordinal not in range(128)
> >
> > , I have a postgresql database like this
> >
> > osm              | osm             | UTF8         | es_CO.utf8 |
> es_CO.utf8
> >
> > My function is:
> >
> >   @app.route('/')
> >   def show_entries():
> >       g.db.execute("SELECT count(*) AS cant, upper(substr(tags ->
> > 'name',0,(strpos(tags -> 'name',' ')))) AS initial  FROM ways WHERE tags
> ?&
> > Array['highway','name'] GROUP BY initial ORDER BY cant DESC, initial")
> >       #cur = g.db.execute("select 1,2")
> >       entries = [dict(name=row[0], cant=row[1]) for row in
> g.db.fetchall()]
> >       return render_template('show_entries.html', entries=entries)
> >
> > The template is
> >
> > {% extends "layout.html" %}
> > {% block body %}
> > <table class=entries>
> > <tr><th>Tipo</th><th>Cantidad</th>
> >   {% for entry in entries %}
> >     <tr><td>{{ entry.name }}</td><td>{{ entry.cant }}</td></tr>
> >   {% else %}
> > <!-- Nothing -->
> >   {% endfor %}
> >   </ul>
> > {% endblock %}
>
> I believe the problem is that Jinja2 is expecting unicode objects[0],
> while your results from the database are UTF-8 encoded str objects.  You
> need to decode them to unicode before passing them to the template,
> e.g.:
>
>  entries = [{
>      'name': row[0].decode('utf-8'),
>      'cant': row[1],
>  } for row in g.db.fetchall()]
>
> [0] http://jinja.pocoo.org/docs/api/#unicode
>
>
You are totally right, thx it solved all :)

P.D.: a more pythonic dic too, cool.


> --
> Audrius Ka┼żukauskas
> http://neutrino.lt/
>