Arda Nalbant
Arda Nalbant

Reputation: 491

Web.py - Unicode :Decode("utf-8") gives error

def search(str):
    cnx = mysql.connector.connect(user='arda', password='1', database='worddb')
    cursor = cnx.cursor()
    sqlq = "SELECT COUNT(1) FROM names WHERE name = '%s'" %str
    cursor.execute(sqlq)
    if cursor.fetchone()[0]:
        return str + " " + "name"
    else:
        return str + " " + "not name"

when I search Ömür it gives me the output = ömür

  1. I declared # -- coding: utf-8 --

2 - tried str.decode("utf-8")

3 - Also I created my database with utf -8

when I try str.decode it gives me ascii error:

'ascii' codec can't encode character u'\xf6' in position 0: ordinal not in range(128)

What is wrong with my code?

Upvotes: 0

Views: 778

Answers (1)

Arda Nalbant
Arda Nalbant

Reputation: 491

The response from the database is already a Unicode. We must assume that Web.py encodes it to UTF-8 on response.

Therefore, you need to add a Content-Type header with the charset set to utf-8 so the browser knows the encoding of the page.

E.g.

web.header('Content-Type','text/html; charset=utf-8', unique=True)

Full Example:

def search(str):
    web.header('Content-Type','text/html; charset=utf-8', unique=True) 
    cnx = mysql.connector.connect(user='arda', password='1', database='worddb')
    cursor = cnx.cursor()
    sqlq = "SELECT COUNT(1) FROM names WHERE name = '%s'" %str
    cursor.execute(sqlq)
    if cursor.fetchone()[0]:
        return str + " " + "name"
    else:
        return str + " " + "not name"

Upvotes: 1

Related Questions