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

Revision 3298, 4.4 kB (checked in by jerome, 16 years ago)

It seems that the lead developer can eat his own food again...
More testing needs to be done but printing should now work again at
least with the PostgreSQL backend.

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