root / pykota / trunk / pykota / utils.py @ 3295

Revision 3295, 4.3 kB (checked in by jerome, 16 years ago)

Made the CGI scripts work again.
Moved even more functions to the utils module.
Removed the cgifuncs module, moved (and changed) content into utils.
If no output encoding defined, use UTF-8 : when wget is used to try
the CGI scripts, it doesn't set by default the accepted charset and
language headers.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# -*- coding: UTF-8 -*-
2#
3# PyKota : Print Quotas for CUPS
4#
5# (c) 2003, 2004, 2005, 2006, 2007, 2008 Jerome Alet <alet@librelogiciel.com>
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program.  If not, see <http://www.gnu.org/licenses/>.
18#
19# $Id$
20#
21
22"""This module defines some utility functions which make no sense as methods."""
23
24import sys
25import os
26import locale
27import gettext
28
29def initlocale(lang="", cset=None) :
30    """Initializes the locale stuff."""
31    try :
32        locale.setlocale(locale.LC_ALL, (lang, cset))
33    except (locale.Error, IOError) :
34        locale.setlocale(locale.LC_ALL, None)
35    (language, charset) = locale.getlocale()
36    language = language or "C"
37    try :
38        charset = charset or locale.getpreferredencoding()
39    except locale.Error :   
40        charset = sys.stdout.encoding or sys.getfilesystemencoding()
41
42    # Dirty hack : if the charset is ASCII, we can safely use UTF-8 instead
43    # This has the advantage of allowing transparent support for recent
44    # versions of CUPS which (en-)force charset to UTF-8 when printing.
45    # This should be needed only when printing, but is probably (?) safe
46    # to do when using interactive commands.
47    if charset.upper() in ('ASCII', 'ANSI_X3.4-1968') :
48        charset = "UTF-8"
49    return (language, charset)
50
51def initgettext(lang, cset) :
52    """Initializes gettext translations for PyKota."""
53    try :
54        try :
55            trans = gettext.translation("pykota", \
56                                        languages=["%s.%s" % (lang, 
57                                                              cset)], 
58                                        codeset=cset)
59        except TypeError : # Python <2.4
60            trans = gettext.translation("pykota", 
61                                        languages=["%s.%s" % (lang, 
62                                                              cset)])
63        trans.install(unicode=True)
64    except :
65        gettext.NullTranslations().install(unicode=True)
66       
67def getpreferredlanguage() :
68    """Returns the preferred language."""
69    languages = os.environ.get("HTTP_ACCEPT_LANGUAGE", "")
70    langs = [l.strip().split(';')[0] for l in languages.split(",")]
71    return langs[0].replace("-", "_")
72   
73def getpreferredcharset() :
74    """Returns the preferred charset."""
75    charsets = os.environ.get("HTTP_ACCEPT_CHARSET", "UTF-8")
76    charsets = [l.strip().split(';')[0] for l in charsets.split(",")]
77    return charsets[0]
78
79def reinitcgilocale() :       
80    """Reinitializes the locale and gettext translations for CGI scripts, according to browser's preferences."""
81    initgettext(*initlocale(getpreferredlanguage(), getpreferredcharset()))
82   
83def N_(message) :
84    """Fake translation marker for translatable strings extraction."""
85    return message
86
87def databaseToUnicode(text) :
88    """Converts from database format (UTF-8) to unicode."""
89    if text is not None :
90        return text.decode("UTF-8", "replace")
91    else : 
92        return None
93   
94def unicodeToDatabase(text) :
95    """Converts from unicode to database format (UTF-8)."""
96    if text is not None : 
97        return text.encode("UTF-8", "replace")
98    else :   
99        return None
100           
101def logerr(text) :
102    """Logs an unicode text to stderr."""
103    sys.stderr.write(text.encode(sys.stdout.encoding or locale.getlocale()[1], \
104                                 "replace"))
105    sys.stderr.flush()
106           
107def crashed(message="Bug in PyKota") :   
108    """Minimal crash method."""
109    import traceback
110    from pykota.version import __version__
111    lines = []
112    for line in traceback.format_exception(*sys.exc_info()) :
113        lines.extend([l for l in line.split("\n") if l])
114    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)])
115    logerr(msg)
116    return msg
Note: See TracBrowser for help on using the browser.