Esempio 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
Esempio 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
Esempio 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')
Esempio 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')
Esempio 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')
Esempio 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')
Esempio 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])
Esempio n. 8
0
File: acl.py Progetto: 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])
Esempio 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)
Esempio 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)
Esempio n. 11
0
def parse_number(string):
    """See :meth:`I18nStore.parse_number`."""
    return get_request().i18n.parse_number(string)
Esempio n. 12
0
def parse_date(string):
    """See :meth:`I18nStore.parse_date`"""
    return get_request().i18n.parse_date(string)
Esempio n. 13
0
def format_percent(number, format=None):
    """See :meth:`I18nStore.format_percent`."""
    return get_request().i18n.format_percent(number, format)
Esempio n. 14
0
def format_decimal(number, format=None):
    """See :meth:`I18nStore.format_decimal`."""
    return get_request().i18n.format_decimal(number, format)
 def number_of_shards(self):
     return self.shards or get_request().app.config[__name__]['shards']
Esempio 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)
Esempio n. 17
0
def format_number(number):
    """See :meth:`I18nStore.format_number`."""
    return get_request().i18n.format_number(number)
Esempio n. 18
0
def set_locale(locale):
    """See :meth:`I18nStore.set_locale`."""
    return get_request().i18n.set_locale(locale)
Esempio n. 19
0
def format_currency(number, currency, format=None):
    """See :meth:`I18nStore.format_currency`."""
    return get_request().i18n.format_currency(number, currency, format)
Esempio n. 20
0
def set_timezone(timezone):
    """See :meth:`I18nStore.set_timezone`."""
    return get_request().i18n.set_timezone(timezone)
Esempio n. 21
0
def format_scientific(number, format=None):
    """See :meth:`I18nStore.format_scientific`."""
    return get_request().i18n.format_scientific(number, format)
Esempio n. 22
0
def gettext(string, **variables):
    """See :meth:`I18nStore.gettext`."""
    return get_request().i18n.gettext(string, **variables)
Esempio n. 23
0
def parse_time(string):
    """See :meth:`I18nStore.parse_time`."""
    return get_request().i18n.parse_time(string)
Esempio n. 24
0
def ngettext(singular, plural, n, **variables):
    """See :meth:`I18nStore.ngettext`."""
    return get_request().i18n.ngettext(singular, plural, n, **variables)
Esempio n. 25
0
def parse_decimal(string):
    """See :meth:`I18nStore.parse_decimal`."""
    return get_request().i18n.parse_decimal(string)
Esempio n. 26
0
def to_local_timezone(datetime):
    """See :meth:`I18nStore.to_local_timezone`."""
    return get_request().i18n.to_local_timezone(datetime)
Esempio n. 27
0
	def number_of_shards(self):
		return self.shards or get_request().app.config[__name__]['shards']
Esempio n. 28
0
def to_utc(datetime):
    """See :meth:`I18nStore.to_utc`."""
    return get_request().i18n.to_utc(datetime)