Ejemplo n.º 1
0
    def __init__(self, app, _globals=None, filters=None):
        self.app = app
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if not kwargs.get('loader'):
            templates_compiled_target = config['templates_compiled_target']
            use_compiled = not app.debug or config['force_use_compiled']

            if templates_compiled_target and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = ModuleLoader(templates_compiled_target)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = FileSystemLoader(config['templates_dir'])

        # Initialize the environment.
        env = Environment(**kwargs)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if enable_i18n:
            # Install i18n.
            from tipfy import i18n
            env.install_gettext_callables(
                lambda x: get_request().i18n.translations.ugettext(x),
                lambda s, p, n: get_request().i18n.translations.ungettext(
                    s, p, n),
                newstyle=True)
            format_functions = {
                'format_date': i18n.format_date,
                'format_time': i18n.format_time,
                'format_datetime': i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            }
            env.globals.update(format_functions)
            env.filters.update(format_functions)

        env.globals['url_for'] = url_for

        after_creation_func = config['after_environment_created']
        if after_creation_func:
            if isinstance(after_creation_func, basestring):
                after_creation_func = import_string(after_creation_func)

            after_creation_func(env)

        environment_created.send(self, environment=env)
        self.environment = env
Ejemplo n.º 2
0
    def __init__(self, app, _globals=None, filters=None):
        self.app = app
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if not kwargs.get('loader'):
            templates_compiled_target = config['templates_compiled_target']
            use_compiled = not app.debug or config['force_use_compiled']

            if templates_compiled_target and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = ModuleLoader(templates_compiled_target)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = FileSystemLoader(config['templates_dir'])

        # Initialize the environment.
        env = Environment(**kwargs)

        if _globals:
            env.globals.update(_globals)

        if filters:
            env.filters.update(filters)

        if enable_i18n:
            # Install i18n.
            from tipfy import i18n
            env.install_gettext_callables(
                lambda x: get_request().i18n.translations.ugettext(x),
                lambda s, p, n: get_request().i18n.translations.ungettext(s,
                    p, n),
                newstyle=True)
            format_functions = {
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            }
            env.globals.update(format_functions)
            env.filters.update(format_functions)

        env.globals['url_for'] = url_for

        after_creation_func = config['after_environment_created']
        if after_creation_func:
            if isinstance(after_creation_func, basestring):
                after_creation_func = import_string(after_creation_func)

            after_creation_func(env)

        environment_created.send(self, environment=env)
        self.environment = env
Ejemplo n.º 3
0
    def test_set_timezone(self):
        request = get_request()
        request.i18n.set_timezone('UTC')
        self.assertEqual(request.i18n.tzinfo.zone, 'UTC')

        request.i18n.set_timezone('America/Chicago')
        self.assertEqual(request.i18n.tzinfo.zone, 'America/Chicago')

        request.i18n.set_timezone('America/Sao_Paulo')
        self.assertEqual(request.i18n.tzinfo.zone, 'America/Sao_Paulo')
Ejemplo n.º 4
0
    def test_set_timezone(self):
        request = get_request()
        request.i18n.set_timezone('UTC')
        self.assertEqual(request.i18n.tzinfo.zone, 'UTC')

        request.i18n.set_timezone('America/Chicago')
        self.assertEqual(request.i18n.tzinfo.zone, 'America/Chicago')

        request.i18n.set_timezone('America/Sao_Paulo')
        self.assertEqual(request.i18n.tzinfo.zone, 'America/Sao_Paulo')
Ejemplo n.º 5
0
    def test_to_local_timezone(self):
        request = get_request()
        request.i18n.set_timezone('US/Eastern')

        format = '%Y-%m-%d %H:%M:%S %Z%z'

        # Test datetime with timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')

        # Test naive datetime - no timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')
Ejemplo n.º 6
0
    def test_to_local_timezone(self):
        request = get_request()
        request.i18n.set_timezone('US/Eastern')

        format = '%Y-%m-%d %H:%M:%S %Z%z'

        # Test datetime with timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0, tzinfo=pytz.UTC)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')

        # Test naive datetime - no timezone set
        base = datetime.datetime(2002, 10, 27, 6, 0, 0)
        localtime = i18n.to_local_timezone(base)
        result = localtime.strftime(format)
        self.assertEqual(result, '2002-10-27 01:00:00 EST-0500')
Ejemplo n.º 7
0
    def get_roles_and_rules(cls, area, user, roles_map, roles_lock):
        """Returns a tuple (roles, rules) for a given user in a given area.

		:param area:
			Area string identifier.
		:param user:
			User string identifier.
		:param roles_map:
			Dictionary of available role names mapping to list of rules.
		:param roles_lock:
			Lock for the roles map: a unique identifier to track changes.
		:returns:
			A tuple of (roles, rules) for the given user in the given area.
		"""
        res = None
        cache_key = cls.get_key_name(area, user)
        if cache_key in _rules_map:
            res = _rules_map[cache_key]
        else:
            res = memcache.get(cache_key, namespace=cls.__name__)

        if res is not None:
            lock, roles, rules = res

        if res is None or lock != roles_lock or get_request().app.debug:
            entity = cls.get_by_key_name(cache_key)
            if entity is None:
                res = (roles_lock, [], [])
            else:
                rules = []
                # Apply role rules.
                for role in entity.roles:
                    rules.extend(roles_map.get(role, []))

                # Extend with rules, eventually overriding some role rules.
                rules.extend(entity.rules)

                # Reverse everything, as rules are checked from last to first.
                rules.reverse()

                # Set results for cache, applying current roles_lock.
                res = (roles_lock, entity.roles, rules)

            cls.set_cache(cache_key, res)

        return (res[1], res[2])
Ejemplo n.º 8
0
Archivo: acl.py Proyecto: acettt/yandex
	def get_roles_and_rules(cls, area, user, roles_map, roles_lock):
		"""Returns a tuple (roles, rules) for a given user in a given area.

		:param area:
			Area string identifier.
		:param user:
			User string identifier.
		:param roles_map:
			Dictionary of available role names mapping to list of rules.
		:param roles_lock:
			Lock for the roles map: a unique identifier to track changes.
		:returns:
			A tuple of (roles, rules) for the given user in the given area.
		"""
		res = None
		cache_key = cls.get_key_name(area, user)
		if cache_key in _rules_map:
			res = _rules_map[cache_key]
		else:
			res = memcache.get(cache_key, namespace=cls.__name__)

		if res is not None:
			lock, roles, rules = res

		if res is None or lock != roles_lock or get_request().app.debug:
			entity = cls.get_by_key_name(cache_key)
			if entity is None:
				res = (roles_lock, [], [])
			else:
				rules = []
				# Apply role rules.
				for role in entity.roles:
					rules.extend(roles_map.get(role, []))

				# Extend with rules, eventually overriding some role rules.
				rules.extend(entity.rules)

				# Reverse everything, as rules are checked from last to first.
				rules.reverse()

				# Set results for cache, applying current roles_lock.
				res = (roles_lock, entity.roles, rules)

			cls.set_cache(cache_key, res)

		return (res[1], res[2])
Ejemplo n.º 9
0
def format_time(time=None, format=None, rebase=True):
    """See :meth:`I18nStore.format_time`."""
    return get_request().i18n.format_time(time, format, rebase)
Ejemplo n.º 10
0
def get_timezone_location(dt_or_tzinfo):
    """See :meth:`I18nStore.get_timezone_location`."""
    return get_request().i18n.get_timezone_location(dt_or_tzinfo)
Ejemplo n.º 11
0
def parse_number(string):
    """See :meth:`I18nStore.parse_number`."""
    return get_request().i18n.parse_number(string)
Ejemplo n.º 12
0
def parse_date(string):
    """See :meth:`I18nStore.parse_date`"""
    return get_request().i18n.parse_date(string)
Ejemplo n.º 13
0
def format_percent(number, format=None):
    """See :meth:`I18nStore.format_percent`."""
    return get_request().i18n.format_percent(number, format)
Ejemplo n.º 14
0
def format_decimal(number, format=None):
    """See :meth:`I18nStore.format_decimal`."""
    return get_request().i18n.format_decimal(number, format)
Ejemplo n.º 15
0
 def number_of_shards(self):
     return self.shards or get_request().app.config[__name__]['shards']
Ejemplo n.º 16
0
def format_timedelta(datetime_or_timedelta, granularity='second',
    threshold=.85):
    """See :meth:`I18nStore.format_timedelta`."""
    return get_request().i18n.format_timedelta(datetime_or_timedelta,
        granularity, threshold)
Ejemplo n.º 17
0
def format_number(number):
    """See :meth:`I18nStore.format_number`."""
    return get_request().i18n.format_number(number)
Ejemplo n.º 18
0
def set_locale(locale):
    """See :meth:`I18nStore.set_locale`."""
    return get_request().i18n.set_locale(locale)
Ejemplo n.º 19
0
def format_currency(number, currency, format=None):
    """See :meth:`I18nStore.format_currency`."""
    return get_request().i18n.format_currency(number, currency, format)
Ejemplo n.º 20
0
def set_timezone(timezone):
    """See :meth:`I18nStore.set_timezone`."""
    return get_request().i18n.set_timezone(timezone)
Ejemplo n.º 21
0
def format_scientific(number, format=None):
    """See :meth:`I18nStore.format_scientific`."""
    return get_request().i18n.format_scientific(number, format)
Ejemplo n.º 22
0
def gettext(string, **variables):
    """See :meth:`I18nStore.gettext`."""
    return get_request().i18n.gettext(string, **variables)
Ejemplo n.º 23
0
def parse_time(string):
    """See :meth:`I18nStore.parse_time`."""
    return get_request().i18n.parse_time(string)
Ejemplo n.º 24
0
def ngettext(singular, plural, n, **variables):
    """See :meth:`I18nStore.ngettext`."""
    return get_request().i18n.ngettext(singular, plural, n, **variables)
Ejemplo n.º 25
0
def parse_decimal(string):
    """See :meth:`I18nStore.parse_decimal`."""
    return get_request().i18n.parse_decimal(string)
Ejemplo n.º 26
0
def to_local_timezone(datetime):
    """See :meth:`I18nStore.to_local_timezone`."""
    return get_request().i18n.to_local_timezone(datetime)
Ejemplo n.º 27
0
	def number_of_shards(self):
		return self.shards or get_request().app.config[__name__]['shards']
Ejemplo n.º 28
0
def to_utc(datetime):
    """See :meth:`I18nStore.to_utc`."""
    return get_request().i18n.to_utc(datetime)