[Twisted-web] how to set charset of html page

Donovan Preston dp at ulaluma.com
Wed Sep 1 14:14:12 MDT 2004


On Sep 1, 2004, at 3:18 PM, Benjamin Ferrari wrote:

> Hello,
>
> I just started with twisted, so I guess this is a very easy question:
>
> I run a twisted.web server with mktap:
>
> % mktap web --path /path/to/content
> % twistd -nf web.tap
>
> and then put a simple html page into the path folder:
>
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
> "DTD/xhtml1-strict.dtd">
> <html xmlns="http://www.w3.org/1999/xhtml">
> <head>
>   <meta http-equiv="Content-Type" content="text/html; 
> charset=iso-8859-1">
> </head>
> <body>...</body>
>
> unfortunately, browsers (tested with firefox 0.9.3 and IE6) completly 
> ignore the <meta/> tag and detect the page as UTF-8 instead of 
> iso-8859-1.
>
> with apache, I can set a default charset to use with
>
> AddDefaultCharset iso-8859-1
>
> How can I do that with the twisted server ?

It's not a terribly easy question, although it should be. The trick is 
modify the contentTypes dictionary on the root twisted.web.static.File 
instance which was created when you ran mktap web. You should be able 
to do this with COIL, which is meant to allow you to configure 
application objects created with mktap using a nice GUI, but COIL 
hasn't been finished and nobody has been working on it recently. You 
could do this with manhole, which gives you a python interpreter inside 
your running server, but it might be a pain to get at the File 
instance.

So here is the solution I came up with. Instead of using mktap to 
create a generic application object, write a tac file instead, which is 
just a Python script that creates a custom application object. Modify 
the contentTypes dictionary in this script. Then, start the server 
using twistd -y instead of -f

Here is the script:

from twisted.application import service, internet
from twisted.web import server, static

application = service.Application("My web server")
root = static.File("/Users/dp")
root.contentTypes['.html'] = 'text/html; charset=iso-8859-1'
internet.TCPServer(8080, 
server.Site(root)).setServiceParent(application)

-- 
Donovan




More information about the Twisted-web mailing list