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

Revision 3310, 4.5 kB (checked in by jerome, 16 years ago)

Added a workaround for buggy versions of python-mysqldb (e.g
1.2.1-p2-4 on my Debian Etch box) which have the double
encoding bug (#1521274 on sourceforge.net).

  • 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
28from types import UnicodeType
29
30def initlocale(lang="", cset=None) :
31    """Initializes the locale stuff."""
32    try :
33        locale.setlocale(locale.LC_ALL, (lang, cset))
34    except (locale.Error, IOError) :
35        locale.setlocale(locale.LC_ALL, None)
36    (language, charset) = locale.getlocale()
37    language = language or "C"
38    try :
39        charset = charset or locale.getpreferredencoding()
40    except locale.Error :   
41        charset = sys.stdout.encoding or sys.getfilesystemencoding()
42
43    if (not charset) or charset in ("ASCII", "ANSI_X3.4-1968") :
44        charset = "UTF-8"
45       
46    return (language, charset)
47
48def setenv(varname, value, charset) :
49    """Sets an environment variable."""
50    if value is None :
51        value = "None"
52    os.environ[varname] = value.encode(charset, "replace")   
53   
54def initgettext(lang, cset) :
55    """Initializes gettext translations for PyKota."""
56    try :
57        try :
58            trans = gettext.translation("pykota", \
59                                        languages=["%s.%s" % (lang, 
60                                                              cset)], 
61                                        codeset=cset)
62        except TypeError : # Python <2.4
63            trans = gettext.translation("pykota", 
64                                        languages=["%s.%s" % (lang, 
65                                                              cset)])
66        trans.install(unicode=True)
67    except :
68        gettext.NullTranslations().install(unicode=True)
69       
70def getpreferredlanguage() :
71    """Returns the preferred language."""
72    languages = os.environ.get("HTTP_ACCEPT_LANGUAGE", "")
73    langs = [l.strip().split(';')[0] for l in languages.split(",")]
74    return langs[0].replace("-", "_")
75   
76def getpreferredcharset() :
77    """Returns the preferred charset."""
78    charsets = os.environ.get("HTTP_ACCEPT_CHARSET", "UTF-8")
79    charsets = [l.strip().split(';')[0] for l in charsets.split(",")]
80    return charsets[0]
81
82def reinitcgilocale() :       
83    """Reinitializes the locale and gettext translations for CGI scripts, according to browser's preferences."""
84    initgettext(*initlocale(getpreferredlanguage(), getpreferredcharset()))
85   
86def N_(message) :
87    """Fake translation marker for translatable strings extraction."""
88    return message
89
90def databaseToUnicode(text) :
91    """Converts from database format (UTF-8) to unicode.
92   
93       We use "replace" to accomodate legacy datas which may not
94       have been recorded correctly.
95    """
96    if text is not None :
97        if not isinstance(text, UnicodeType) :
98            return text.decode("UTF-8", "replace")
99        else :   
100            # MySQL already returns unicode objects
101            return text
102    else : 
103        return None
104   
105def unicodeToDatabase(text) :
106    """Converts from unicode to database format (UTF-8)."""
107    if text is not None : 
108        return text.encode("UTF-8")
109    else :   
110        return None
111           
112def logerr(text) :
113    """Logs an unicode text to stderr."""
114    sys.stderr.write(text.encode(sys.stdout.encoding \
115                                     or locale.getlocale()[1] \
116                                     or "ANSI_X3.4-1968", \
117                                 "replace"))
118    sys.stderr.flush()
119           
120def crashed(message="Bug in PyKota") :   
121    """Minimal crash method."""
122    import traceback
123    from pykota.version import __version__
124    lines = []
125    for line in traceback.format_exception(*sys.exc_info()) :
126        lines.extend([l for l in line.split("\n") if l])
127    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKota v%s" % __version__, message] + lines)])
128    logerr(msg)
129    return msg
Note: See TracBrowser for help on using the browser.