kd1978
kd1978

Reputation: 511

Python encoding issue (ascii > unicode)

I am having a typical utf-8 encoding issue, but so far I haven't been able to resolve it.

class StatsTandE(webapp2.RequestHandler):
  def get(self):

    conn = rdbms.connect(instance=_INSTANCE_NAME, database='origami')
    cursor = conn.cursor()
    cursor.execute('SELECT ui.displayName, ui.title, ui.costCenter FROM views AS v')
    results = [[str(row[0]), str(row[1]), str(row[2])] for row in cursor.fetchall()]
    logging.info('results identified as %s', results)

    template_file_name = 'templates/stats_results.html'
    template_values = {
      'results': results,
    }

    path = os.path.join(os.path.dirname(__file__), template_file_name)
    self.response.out.write(template.render(path, template_values))
    conn.close()

The error I am seeing is:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 4: ordinal not in range(128)

Changing str(row[0]) to str(row[0]).encode('utf-8') didn't work...

Any suggestions?

Upvotes: 0

Views: 973

Answers (1)

maddyblue
maddyblue

Reputation: 16882

Try changing str(row[0]) to unicode(row[0]).

Update: As others have stated: you should not even be using unicode and str unless you need it. Try just row[0], row[1], row[2]. When you need to display it, do something like this: row[0].encode('utf8').

Upvotes: 1

Related Questions