[mod_python] How to set utf-8 charset from mod_python?

Julien Cigar jcigar at ulb.ac.be
Thu Feb 1 05:26:32 EST 2007


export at hope.cz wrote:
>   
>> Like req.write(' <html>....').encode('utf-8')
>>
>> Or
>>
>> Def do_some_processing(Req):
>>  Req.return_html+="<!-- -->\n"
>>
>> Handler(Req):
>>  Req.return_html=""
>>  Req.return_html+="<html>....\n"
>>       do_some_processing(Req)
>>  Req.write(Req.return_html).encode('utf-8')
>>  ......
>>
>>
>> Martijn
>>     
>
> Martin,
> Thank you for your reply.
>   
>> req.write(' <html>....').encode('utf-8') 
>>     
> That  does not work for me. I receive the error:
> AttributeError: 'NoneType' object has no attribute 'encode' 
>
>   

You must have a string.
 >>> None.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'NoneType' object has no attribute 'encode'

> I normally use
> <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
>   

This is not "valid" anymore in xhtml.

Also it is recommended to have an xml declaration at the top of your file
<?xml version="1.0" encoding="utf-8" standalone="no" ?>

with a proper DTD :

<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

and something like :

<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml"


> in my HTRL page but it does NOT work with mod_python handler for me.
> When I open the page in a browser and check the Encoding from  the browser menu,
> it is set to Western European(ISO) not to UTF-8.
>
> Where can be a problem?
>   

First, be sure that the content-type header is set with the following :
req.content_type = 'text/html ; charset=utf-8'

Second, be sure that your Python function returns an Unicode object :
 >>> 'fooé'.encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: 
ordinal not in range(128)
 >>> u'fooé'.encode('utf-8')
'foo\xc3\xa9'

If you use a template engine, there are maybe things to do too :
For example in Genshi : stream.render(method='xhtml', encoding='utf-8')

> Thank you for hel
> Lad.
>
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python
>   

Regards,
Julien

-- 
Julien Cigar
Belgian Biodiversity Platform
http://www.biodiversity.be
Université Libre de Bruxelles
Campus de la Plaine CP 257
Bâtiment NO, Bureau 4 N4 115C (Niveau 4)
Boulevard du Triomphe, entrée ULB 2
B-1050 Bruxelles
office: jcigar at ulb.ac.be



More information about the Mod_python mailing list