Re: Patch to add support for locales (for localized dates)

Martijn van de Streek <[email protected]>
Newsgroups gmane.comp.web.pyblosxom.devel
Message-ID <[email protected]>
On Sun, 03 Sep 2006, Martijn van de Streek wrote:

> I've made a patch that adds locale support to PyBlosxom 1.3.2. It's
> backwards compatible if you don't have a py['locale'] key in your
> config.py, but if you have it, pyblosxom will switch to the specified
> locale before doing anything else.

Here's the updated patch.

It initializes the globals (num2month, month2num, MONTHS; why are these
globals anyway?) in the tools.initialize function, so they get filled
only after the locale is set.

As the variables aren't used before tools.initialize is called,
everything else should continue to work.

It's a new patch against clean 1.3.2 (so it probably won't apply if
you've already applied the previous patch)

Martijn
-- 
Sorry isn't an excuse when you do something stupid on purpose.

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642

_______________________________________________
Pyblosxom-devel mailing list
Pyblosxom-devel-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
https://lists.sourceforge.net/lists/listinfo/pyblosxom-devel
pyblosxom-locales.patch (text/plain, 7.1 KB)
diff -ur pyblosxom-1.3.2/Pyblosxom/entries/base.py pyblosxom-1.3.2-locale/Pyblosxom/entries/base.py
--- pyblosxom-1.3.2/Pyblosxom/entries/base.py	2006-02-02 20:47:05.000000000 +0100
+++ pyblosxom-1.3.2-locale/Pyblosxom/entries/base.py	2006-09-03 15:01:38.000000000 +0200
@@ -8,7 +8,7 @@
 This module also holds a generic generate_entry function which will generate
 a BaseEntry with data that you provide for it.
 """
-import time, urllib
+import time, urllib, locale
 from Pyblosxom import tools
 
 BIGNUM = 2000000000
@@ -192,10 +192,18 @@
         self['dw'] = time.strftime('%A', timeTuple)
         self['yr'] = time.strftime('%Y', timeTuple)
         self['fulltime'] = time.strftime('%Y%m%d%H%M%S', timeTuple)
+        self['date'] = time.strftime('%a, %d %b %Y', timeTuple)
+       
+        # Temporarily disable the set locale, so RFC-compliant dates are really
+        # RFC-compliant
+        loc = locale.getlocale(locale.LC_ALL)
+        locale.setlocale(locale.LC_ALL, 'C')
+        
         # YYYY-MM-DDThh:mm:ssZ
         self['w3cdate'] = time.strftime('%Y-%m-%dT%H:%M:%SZ', gmTimeTuple)
         self['rfc822date'] = time.strftime('%a, %d %b %Y %H:%M GMT', gmTimeTuple)
-        self['date'] = time.strftime('%a, %d %b %Y', timeTuple)
+        
+        locale.setlocale(locale.LC_ALL, loc)
 
     def __getitem__(self, key, default=None):
         """
diff -ur pyblosxom-1.3.2/Pyblosxom/pyblosxom.py pyblosxom-1.3.2-locale/Pyblosxom/pyblosxom.py
--- pyblosxom-1.3.2/Pyblosxom/pyblosxom.py	2006-09-07 14:55:45.000000000 +0200
+++ pyblosxom-1.3.2-locale/Pyblosxom/pyblosxom.py	2006-09-03 15:07:08.000000000 +0200
@@ -6,6 +6,7 @@
 # Python imports
 from __future__ import nested_scopes, generators
 import os, time, re, sys
+import locale
 import cgi
 try: from cStringIO import StringIO
 except ImportError: from StringIO import StringIO
@@ -66,6 +67,12 @@
         pyhttp = self._request.getHttp()
         config = self._request.getConfiguration()
 
+        # Initialize the locale, if wanted (will silently fail if locale is not
+        # available)
+        if config.get('locale'):
+            try: locale.setlocale(locale.LC_ALL, config['locale'])
+            except locale.Error: pass # Invalid locale 
+
         # initialize the tools module
         tools.initialize(config)
 
@@ -821,9 +828,16 @@
     mtime_gmtuple = time.gmtime(mtime)
 
     data["latest_date"] = time.strftime('%a, %d %b %Y', mtime_tuple)
+
+    # Make sure we get proper 'English' dates when using standards 
+    loc = locale.getlocale(locale.LC_ALL)
+    locale.setlocale(locale.LC_ALL, 'C')
+    
     data["latest_w3cdate"] = time.strftime('%Y-%m-%dT%H:%M:%SZ', mtime_gmtuple)
     data['latest_rfc822date'] = time.strftime('%a, %d %b %Y %H:%M GMT', mtime_gmtuple)
 
+    locale.setlocale(locale.LC_ALL, loc)
+
     # we pass the request with the entry_list through the prepare callback
     # giving everyone a chance to transform the data.  the request is
     # modified in place.
@@ -1146,14 +1160,13 @@
         data['blog_title_with_path'] = blog_title
 
     # construct our final URL
+    data['url'] = '%s%s' % (config['base_url'], data['pi_bl'])
     url = config['base_url']
     if data['pi_bl'].startswith("/"):
         url = url + data['pi_bl']
     else:
         url = url + "/" + data['pi_bl']
-
     data['url'] = url
-    data['full_url'] = url
 
     # set path_info to our latest path_info
     data['path_info'] = path_info
diff -ur pyblosxom-1.3.2/Pyblosxom/tools.py pyblosxom-1.3.2-locale/Pyblosxom/tools.py
--- pyblosxom-1.3.2/Pyblosxom/tools.py	2005-12-14 05:51:31.000000000 +0100
+++ pyblosxom-1.3.2-locale/Pyblosxom/tools.py	2006-09-10 08:30:18.000000000 +0200
@@ -10,6 +10,7 @@
 """
 import plugin_utils
 import sgmllib, re, os, types, time, os.path, sys, urllib
+import locale
 
 __revision__ = "$Id: tools.py,v 1.50 2005/12/09 05:09:11 willhelm Exp $"
 
@@ -18,30 +19,9 @@
 except ImportError:
     from cgi import escape
 
-
-month2num = { 'nil' : '00',
-              'Jan' : '01',
-              'Feb' : '02',
-              'Mar' : '03',
-              'Apr' : '04',
-              'May' : '05',
-              'Jun' : '06',
-              'Jul' : '07',
-              'Aug' : '08',
-              'Sep' : '09',
-              'Oct' : '10',
-              'Nov' : '11',
-              'Dec' : '12'}
-
-# This is not python 2.1 compatible (Nifty though)
-# num2month = dict(zip(month2num.itervalues(), month2num))
-num2month = {}
-for month_abbr, month_num in month2num.items():
-    num2month[month_num] = month_abbr
-    num2month[int(month_num)] = month_abbr
-
-# all the valid month possibilities
-MONTHS = num2month.keys() + month2num.keys()
+month2num = None
+num2month = None
+MONTHS    = None
 
 # regular expression for detection and substituion of variables.
 VAR_REGEXP = re.compile(ur'(?<!\\)\$((?:\w|\-|::\w)+(?:\(.*?(?<!\\)\))?)')
@@ -54,11 +34,44 @@
     """
     Initialize the tools module. This gives the module a chance to use 
     configuration from the pyblosxom config.py file.
+    
+    It also initialises the month2num and num2month dicts: they need to
+    be created after the locale is first set, if we want them to contain
+    the proper month names.
+    
     This should be called from Pyblosxom.pyblosxom.PyBlosxom.initialize.
     """
     global _config
     _config = config
 
+    # Month names tend to differ with locale
+    global month2num
+    month2num = { 'nil' : '00',
+                  locale.nl_langinfo(locale.ABMON_1) : '01',
+                  locale.nl_langinfo(locale.ABMON_2) : '02',
+                  locale.nl_langinfo(locale.ABMON_3) : '03',
+                  locale.nl_langinfo(locale.ABMON_4) : '04',
+                  locale.nl_langinfo(locale.ABMON_5) : '05',
+                  locale.nl_langinfo(locale.ABMON_6) : '06',
+                  locale.nl_langinfo(locale.ABMON_7) : '07',
+                  locale.nl_langinfo(locale.ABMON_8) : '08',
+                  locale.nl_langinfo(locale.ABMON_9) : '09',
+                  locale.nl_langinfo(locale.ABMON_10) : '10',
+                  locale.nl_langinfo(locale.ABMON_11) : '11',
+                  locale.nl_langinfo(locale.ABMON_12) : '12'}
+    
+    # This is not python 2.1 compatible (Nifty though)
+    # num2month = dict(zip(month2num.itervalues(), month2num))
+    global num2month
+    num2month = {}
+    for month_abbr, month_num in month2num.items():
+        num2month[month_num] = month_abbr
+        num2month[int(month_num)] = month_abbr
+    
+    # all the valid month possibilities
+    global MONTHS
+    MONTHS = num2month.keys() + month2num.keys()
+
 def cleanup():
     """
     Cleanup the tools module.
diff -ur pyblosxom-1.3.2/web/config.py pyblosxom-1.3.2-locale/web/config.py
--- pyblosxom-1.3.2/web/config.py	2006-01-30 15:48:39.000000000 +0100
+++ pyblosxom-1.3.2-locale/web/config.py	2006-09-03 14:35:44.000000000 +0200
@@ -8,6 +8,11 @@
 # directory.
 #py["codebase"] = "/path/to/pyblosxom/installation"
 
+# What's the locale for the blog? This affects things like the format of dates,
+# etc.
+# Make sure the locale is valid for your system.
+#py["locale"] = "nl_NL.UTF-8"
+
 # What's this blog's title?
 py['blog_title'] = "Another pyblosxom blog"
signature.asc (application/pgp-signature, 191 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)

iD8DBQFFA7ISDafvoz+l4DERAktcAJ9f3KD5JhNzLC+sVsw7STIb2+q8xQCghghA
3SmbDTS0tNWAs/jLOGQGQr8=
=G+aG
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.