locale.format -> babel.numbers.format_number

This commit is contained in:
Neil Williams
2012-05-16 20:06:28 -07:00
parent c9c1bc6fec
commit a97c2af1ad
11 changed files with 52 additions and 33 deletions

View File

@@ -46,6 +46,7 @@ from hashlib import sha1, md5
from urllib import quote, unquote
import simplejson
import locale, socket
import babel.core
from r2.lib.tracking import encrypt, decrypt
from pylons import Response
@@ -388,6 +389,11 @@ def set_iface_lang():
#we don't have a translation for that language
h.set_lang(g.lang, graceful_fail = True)
try:
c.locale = babel.core.Locale.parse(c.lang, sep='-')
except (babel.core.UnknownLocaleError, ValueError):
c.locale = babel.core.Locale.parse(g.lang, sep='-')
#TODO: add exceptions here for rtl languages
if c.lang in ('ar', 'he', 'fa'):
c.lang_rtl = True

View File

@@ -19,7 +19,7 @@
# All portions of the code written by CondeNet are Copyright (c) 2006-2010
# CondeNet, Inc. All Rights Reserved.
################################################################################
import math, datetime, locale
import math, datetime
def google_extended(n):
"""Computes the google extended encoding of an int in [0, 4096)"""
@@ -174,7 +174,7 @@ class LineGraph(object):
def make_labels(i, m, p = 4):
return (("%d:|" % i) +
'|'.join(locale.format('%d', i * m / p, True)
'|'.join(str(i * m / p)
for i in range(p+1)))
# data stores a list of xy data strings in google's format

View File

@@ -50,7 +50,7 @@ from r2.lib.strings import plurals, rand_strings, strings, Score
from r2.lib.utils import title_to_url, query_string, UrlParser, to_js, vote_hash
from r2.lib.utils import link_duplicates, make_offset_date, to_csv, median, to36
from r2.lib.utils import trunc_time, timesince, timeuntil
from r2.lib.template_helpers import add_sr, get_domain
from r2.lib.template_helpers import add_sr, get_domain, format_number
from r2.lib.subreddit_search import popular_searches
from r2.lib.scraper import get_media_embed
from r2.lib.log import log_text
@@ -58,7 +58,7 @@ from r2.lib.memoize import memoize
from r2.lib.utils import trunc_string as _truncate
from r2.lib.filters import safemarkdown
import sys, random, datetime, locale, calendar, simplejson, re, time
import sys, random, datetime, calendar, simplejson, re, time
import graph, pycountry, time
from itertools import chain
from urllib import quote
@@ -3261,14 +3261,14 @@ class PromotedTraffic(Traffic):
if len(imp) > 2:
imp_total = sum(x[2] for x in imp)
self.totals[1] = max(self.totals[1], imp_total)
imp_total = locale.format('%d', imp_total, True)
imp_total = format_number(imp_total)
self.imp_graph = TrafficGraph(imp[-72:], ylabels = ['uniques', 'total'],
title = ("recent impressions (%s total)" %
imp_total))
cli = self.slice_traffic(self.traffic, 2, 3)
cli_total = sum(x[2] for x in cli)
self.totals[3] = max(self.totals[3], cli_total)
cli_total = locale.format('%d', cli_total, True)
cli_total = format_number(cli_total)
self.cli_graph = TrafficGraph(cli[-72:], ylabels = ['uniques', 'total'],
title = ("recent clicks (%s total)" %
cli_total))
@@ -3281,9 +3281,10 @@ class PromotedTraffic(Traffic):
Templated.__init__(self)
def to_iter(self, localize = True, total = False):
locale = c.locale
def num(x):
if localize:
return locale.format('%d', x, True)
return format_number(x, locale)
return str(x)
def row(label, data):
uimp, nimp, ucli, ncli = data
@@ -3414,10 +3415,11 @@ class RedditTraffic(Traffic):
user_scale = ( (day_mean * month_len) /
(last_mean * lastmonthlen) )
last_month_users = 0
locale = c.locale
for x, (date, d) in enumerate(data):
res.append([("date", date.strftime("%Y-%m")),
("", locale.format("%d", d[0], True)),
("", locale.format("%d", d[1], True))])
("", format_number(d[0], locale)),
("", format_number(d[1], locale))])
last_d = data[x-1][1] if x else None
for i in range(2):
# store last month's users for this month's projection
@@ -3435,7 +3437,7 @@ class RedditTraffic(Traffic):
else:
scaled = float(d[i] * month_len) / yday
res[-1].append(("gray",
locale.format("%d", scaled, True)))
format_number(scaled, locale)))
elif last_d and d[i] and last_d[i]:
f = 100 * (float(d[i])/last_d[i] - 1)
@@ -3740,9 +3742,10 @@ class Promote_Graph(Templated):
promote_blocks = sorted_blocks)
def to_iter(self, localize = True):
locale = c.locale
def num(x):
if localize:
return locale.format('%d', x, True)
return format_number(x, locale)
return str(x)
for link, uimp, nimp, ucli, ncli in self.recent:
yield (link._date.strftime("%Y-%m-%d"),

View File

@@ -28,9 +28,10 @@ hooks to the UI are the same.
"""
import r2.lib.helpers as h
from pylons import g
from pylons import g, c
from pylons.i18n import _, ungettext
import random, locale
import random
import babel.numbers
__all__ = ['StringHandler', 'strings', 'PluralManager', 'plurals',
'Score', 'rand_strings']
@@ -279,7 +280,7 @@ class Score(object):
@staticmethod
def _people(x, label):
return strings.person_label % \
dict(num = locale.format("%d", x, True),
dict(num = babel.numbers.format_number(x, c.locale),
persons = label(x))
@staticmethod

View File

@@ -25,6 +25,7 @@ from r2.lib.utils import vote_hash, UrlParser, timesince, is_subdomain
from r2.lib.media import s3_direct_url
import babel.numbers
from mako.filters import url_escape
import simplejson
import os.path
@@ -505,3 +506,10 @@ def add_attr(attrs, kind, label=None, link=None, cssclass=None, symbol=None):
raise ValueError ("Got weird kind [%s]" % kind)
attrs.append( (priority, symbol, cssclass, label, link, img) )
def format_number(number, locale=None):
if not locale:
locale = c.locale
return babel.numbers.format_number(number, locale=locale)

View File

@@ -20,8 +20,8 @@
## CondeNet, Inc. All Rights Reserved.
################################################################################
<%!
import locale
from r2.lib.strings import strings
from r2.lib.template_helpers import format_number
%>
@@ -42,7 +42,7 @@
</div>
<div class="score">
${unsafe(strings.person_label % dict(num = locale.format("%d", thing.a.score, True),
${unsafe(strings.person_label % dict(num = format_number(thing.a.score),
persons = ungettext("point", "points",
thing.a.score)))}
<% percent = int(float(thing.a.upvotes) / max(thing.a.upvotes + thing.a.downvotes, 1) * 100) %>
@@ -50,13 +50,13 @@
</div>
<span class="upvotes">
${unsafe(strings.person_label % dict(num = locale.format("%d", thing.a.upvotes, True),
${unsafe(strings.person_label % dict(num = format_number(thing.a.upvotes),
persons = ungettext("up vote", "up votes",
thing.a.upvotes)))}
</span>
&#32;
<span class="downvotes">
${unsafe(strings.person_label % dict(num = locale.format("%d", thing.a.downvotes, True),
${unsafe(strings.person_label % dict(num = format_number(thing.a.downvotes),
persons = ungettext("down vote", "down votes",
thing.a.downvotes)))}
</span>

View File

@@ -21,9 +21,8 @@
################################################################################
<%!
import locale
from r2.lib.filters import edit_comment_filter, unsafe, safemarkdown
from r2.lib.template_helpers import static
from r2.lib.template_helpers import static, format_number
%>
<%namespace file="utils.html" import="submit_form, plain_link, thing_timestamp"/>
<%namespace file="printablebuttons.html" import="toggle_button"/>
@@ -58,12 +57,12 @@
</div>
%endif
<span class="karma">${locale.format("%d", thing.user.safe_karma, True)}</span>
<span class="karma">${format_number(thing.user.safe_karma)}</span>
&#32;
${_("link karma")}
<br/>
<span class="karma comment-karma">${locale.format("%d", thing.user.comment_karma, True)}</span>
<span class="karma comment-karma">${format_number(thing.user.comment_karma)}</span>
&#32;
${_("comment karma")}

View File

@@ -20,14 +20,17 @@
## CondeNet, Inc. All Rights Reserved.
################################################################################
<%!
from r2.lib.template_helpers import static
from r2.lib.template_helpers import static, format_number
from r2.lib import js
import datetime, locale
import datetime
from r2.lib import promote
import babel.numbers
locale = c.locale
def num(x):
return locale.format('%d', x, True)
return format_number(x, locale)
def money(x):
return "$%.2f" % x
return babel.numbers.format_currency(x, 'USD', locale)
%>
<h1>Sponsored link calendar</h1>

View File

@@ -20,12 +20,12 @@
## CondeNet, Inc. All Rights Reserved.
################################################################################
<%!
from r2.lib.template_helpers import static
from r2.lib.template_helpers import static, format_number
from r2.lib import js
import locale
from r2.models.subreddit import DomainSR, FakeSubreddit
locale = c.locale
def num(x):
return locale.format('%d', x, True)
return format_number(x, locale)
%>
${unsafe(js.use('flot'))}

View File

@@ -20,12 +20,12 @@
## CondeNet, Inc. All Rights Reserved.
################################################################################
<%!
from r2.lib.template_helpers import static
from r2.lib.template_helpers import static, format_number
from r2.lib import js
import locale
from r2.models.subreddit import DomainSR, FakeSubreddit
locale = c.locale
def num(x):
return locale.format('%d', x, True)
return format_number(x, locale)
%>
${unsafe(js.use('flot'))}

View File

@@ -21,7 +21,6 @@
################################################################################
<%!
import locale
from r2.lib.strings import strings, Score
from r2.lib.pages import WrappedUser, ModList
%>