473,809 Members | 2,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

web app breakage with utf-8

Hello, after two days of failed efforts and googling, I thought I had
better seek advice or observations from the experts. I would be grateful
for any input.

We have various small internal web applications that use utf-8 pages for
storing, searching and retrieving user input. They have worked fine for
years with non ASCII values, including Russian, Greek and lots of accented
characters. They still do on an old version of python (2.2.1), and there's
nothing in the code to decode/encode the input, it's *just worked*.

Recently however, while testing on a dev machine, I notice that any
characters outside ASCII are causing SQL statement usage to break with
UnicodeDecodeEr ror exceptions with newer versions of python (2.3 and 2.4).
There are a number of threads online, suggesting converting to unicode
types, and similar themes, but I'm having no success. I am probably
completely misunderstaning something fundamental. :-(

My first question is did something change for normal byte stream usage
making it more strict? I'm surprised there aren't more problems
like this online.

Is there a correct way to handle text input from a <FORMwhen the page is
utf-8 and that input is going to be used in SQL statements? I've tried
things like (with no success):
sql = u"select * from blah where col='%s'" % input

Doing sql = sql.decode('lat in1') prior to execution prevents the
some UnicodeDecodeEr ror exceptions, but the data retrieved from the tables
is no longer usable, causing breakage when being used to create the output
for the browser.
I really am at a loss for what is going wrong, when everything works fine
on crusty old 2.2.1. What are others doing for caputre, store, and output
for web utf-8?
Rgds,
Jason

Jul 6 '06 #1
4 1464
elmo wrote:
Hello, after two days of failed efforts and googling, I thought I had
better seek advice or observations from the experts. I would be grateful
for any input.

We have various small internal web applications that use utf-8 pages for
storing, searching and retrieving user input. They have worked fine for
years with non ASCII values, including Russian, Greek and lots of accented
characters. They still do on an old version of python (2.2.1), and there's
nothing in the code to decode/encode the input, it's *just worked*.

Recently however, while testing on a dev machine, I notice that any
characters outside ASCII are causing SQL statement usage to break with
UnicodeDecodeEr ror exceptions with newer versions of python (2.3 and 2.4).
There are a number of threads online, suggesting converting to unicode
types, and similar themes, but I'm having no success. I am probably
completely misunderstaning something fundamental. :-(

My first question is did something change for normal byte stream usage
making it more strict? I'm surprised there aren't more problems
like this online.

Is there a correct way to handle text input from a <FORMwhen the page is
utf-8 and that input is going to be used in SQL statements? I've tried
things like (with no success):
sql = u"select * from blah where col='%s'" % input
What about " ... % unicode(input, "UTF-8")" ?

Doing sql = sql.decode('lat in1') prior to execution prevents the
some UnicodeDecodeEr ror exceptions, but the data retrieved from the tables
is no longer usable, causing breakage when being used to create the output
for the browser.

I really am at a loss for what is going wrong, when everything works fine
on crusty old 2.2.1. What are others doing for caputre, store, and output
for web utf-8?
You didn't tell us what database you are using, which encoding your database
uses, which Python-DB interface library you deploy, and lots of other things
that might be helpful to solve your problem.

Stefan
Jul 6 '06 #2
On Thu, 06 Jul 2006 19:16:53 +0200, Stefan Behnel wrote:
>>
Is there a correct way to handle text input from a <FORMwhen the page is
utf-8 and that input is going to be used in SQL statements? I've tried
things like (with no success):
sql = u"select * from blah where col='%s'" % input

What about " ... % unicode(input, "UTF-8")" ?

I guess it's similar, I've had partial success with input.decode('u tf-8')
before DB usage, and then output.encode(' utf-8') for output. But although
this stores and displays newly added utf-8 texts correctly, it
causes other problems when displaying the existing texts. I think
they're suffering from a double encoding issue. It seems rather
strange the encode/decode appears to be required now, and not before.
Is this how it should be done?
>
You didn't tell us what database you are using, which encoding your
database uses, which Python-DB interface library you deploy, and lots of
other things that might be helpful to solve your problem.
That would be MySQLdb with latin1, but I've tried various methods to make
it utf-8 (lots of guidance online). But this was only after I discovered
the breakage with the newer python. I.e. it has worked for years on both
machines and various python versions. I omitted that info because I can
paste the SQL into mysql's shell, it does the expected thing with no
errors, so I assumed the DB itself isn't the cause. I guess it could
be a new MySQLdb issue causing breakage.
I feel I can see part of the light, but if I'm close to what I think
is needed, it's not practical to change everything to handle encode/decode
site wide, especially as some of the data gets moved to Oracle for other
applications (most is written in Perl).

I'm thinking I need to do this now, is this the norm?:

get user input from web
text.encode('ut f-8')
store or use as search in DB
text.decode('ut f-8')
display page etc

The encode/decode stages have never been required before :-(

>
Stefan
Jul 6 '06 #3
On Thu, 06 Jul 2006 19:41:32 +0000, elmo wrote:
I guess it could be a new MySQLdb issue causing breakage.
Replying to self, this is *very* close to the problem:
http://sourceforge.net/tracker/index...07&atid=374932
Jul 6 '06 #4
replacing connection.char acter_set_name instance method seems to work
but is this the correct/preferred way?
>>import MySQLdb
MySQLdb.get_c lient_info()
'4.1.8'
>>import sys
sys.version
'2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]'
>>sys.platfor m
'win32'
>>cred = {'passwd': 'secret', 'host': 'myhost', 'db': 'mydb', 'user': 'justin'}
insert = 'insert into unicodetest2 (foo) values (%s)'
alpha = u'\N{GREEK SMALL LETTER ALPHA}'
alpha
u'\u03b1'
>>conn.close( )
conn = MySQLdb.connect (**cred)
cur = conn.cursor()
cur.execute(i nsert, 'a')
1L
>>conn.commit ()
conn.close( )
conn = MySQLdb.connect (**cred)
cur = conn.cursor()
cur.execute(s elect)
1L
>>cur.fetchall( )
((9L, 'a'),)
>>conn.close( )
conn = MySQLdb.connect (**cred)
cur = conn.cursor()
cur.execute(i nsert, alpha)
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "E:\Python23\Li b\site-packages\MySQLd b\cursors.py", line 95, in
execute
return self._execute(q uery, args)
File "E:\Python23\Li b\site-packages\MySQLd b\cursors.py", line 114, in
_execute
self.errorhandl er(self, exc, value)
File "E:\Python23\Li b\site-packages\MySQLd b\connections.p y", line 33,
in defaulterrorhan dler
raise errorclass, errorvalue
LookupError: unknown encoding: latin1_swedish_ ci
>>conn.close( )
conn = MySQLdb.connect (**cred)
def character_set_n ame(*args, **kwargs): return 'utf-8'
....
>>character_set _name()
'utf-8'
>>conn.close( )
conn = MySQLdb.connect (**cred)
conn.characte r_set_name()
'latin1_swedish _ci'
>>import new
conn.characte r_set_name = new.instancemet hod(character_s et_name, conn, conn.__class__)
conn.characte r_set_name()
'utf-8'
>>cur = conn.cursor()
cur.execute(i nsert, alpha)
1L
>>conn.close( )
conn = MySQLdb.connect (**cred)
conn.characte r_set_name()
'latin1_swedish _ci'
>>cur = conn.cursor()
cur.execute(s elect)
2L
>>cur.fetchall( )
((10L, '\xce\xb1'), (9L, 'a'))
>>conn.close( )
conn = MySQLdb.connect (unicode='utf-8', **cred)
conn.characte r_set_name()
'latin1_swedish _ci'
>>cur = conn.cursor()
cur.execute(s elect)
2L
>>cur.fetchall( )
((10L, u'\u03b1'), (9L, u'a'))
>>conn.close( )
conn = MySQLdb.connect (**cred)
cur = conn.cursor()
cur.execute(s elect)
2L
>>cur.fetchall( )
((10L, '\xce\xb1'), (9L, 'a'))
>>conn.close( )
Jul 7 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4194
by: lawrence | last post by:
Someone on www.php.net suggested using a seems_utf8() method to test text for UTF-8 character encoding but didn't specify how to write such a method. Can anyone suggest a test that might work? Something that maybe gives 90% confidence that a given block of text is or is not UTF-8 encoded?
4
6414
by: Alban Hertroys | last post by:
Another python/psycopg question, for which the solution is probably quite simple; I just don't know where to look. I have a query that inserts data originating from an utf-8 encoded XML file. And guess what, it contains utf-8 encoded characters... Now my problem is that psycopg will only accept queries of type str, so how do I get my utf-8 encoded data into the DB? I can't do query.encode('ascii'), that would be similar to: >>> x =...
12
8235
by: Mike Dee | last post by:
A very very basic UTF-8 question that's driving me nuts: If I have this in the beginning of my Python script in Linux: #!/usr/bin/env python # -*- coding: UTF-8 -*- should I - or should I not - be able to use non-ASCII characters in strings and in Tk GUI button labels and GUI window titles and in raw_input data without Python returning wrong case in manipulated
38
5750
by: Haines Brown | last post by:
I'm having trouble finding the character entity for the French abbreviation for "number" (capital N followed by a small supercript o, period). My references are not listing it. Where would I find an answer to this question (don't find it in the W3C_char_entities document). -- Haines Brown brownh@hartford-hwp.com
6
18768
by: jmgonet | last post by:
Hello everybody, I'm having troubles loading a Xml string encoded in UTF-8. If I try this code: ------------------------------ XmlDocument doc=new XmlDocument(); String s="<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><a>Schönbühl</a>"; doc.LoadXml(s); doc.Save("d:\\temp\\test.xml");
6
13895
by: archana | last post by:
Hi all, can someone tell me difference between unicode and utf 8 or utf 18 and which one is supporting more character set. whic i should use to support character ucs-2. I want to use ucs-2 character in streamreader and streamwriter. How unicode and utf chacters are stored.
7
12156
by: Jimmy Shaw | last post by:
Hi everybody, Is there any SIMPLE way to convert from UTF-16 to UTF-32? I may be mixed up, but is it possible that all UTF-16 "code points" that are 16 bits long appear just the same in UTF-32, but with zero padding and hence no real conversion is necessary? If I am completely wrong and some intricate conversion operation needs to take place, can anyone give me some primer on the subject?
10
19587
by: Jed | last post by:
I have a form that needs to handle international characters withing the UTF-8 character set. I have tried all the recommended strategies for getting utf-8 characters from form input to email message and I cannot get it to work. I need to stay with classic asp for this. Here are some things I tried: 'CDONTS Call msg.SetLocaleIDs(65001)
23
5035
by: Allan Ebdrup | last post by:
I hava an ajax web application where i hvae problems with UTF-8 encoding oc chineese chars. My Ajax webapplication runs in a HTML page that is UTF-8 Encoded. I copy and paste some chineese chars from another HTML page viewed in IE7, that is also UTF-8 encoded (search for "china" on google.com). I paste the chineese chars into a content editable div. My Ajax webservice compiles an XML where the data from the content editable div is...
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10378
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10391
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10121
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7664
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4333
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.