Example #1
0
def url(tgpath, tgparams=None, **kw):
    """Computes URLs.

    tgpath can be a list or a string. If the path is absolute (starts
    with a "/"), the server.webpath and the approot of the application
    are prepended to the path. In order for the approot to be
    detected properly, the root object should extend
    controllers.RootController.

    Query parameters for the URL can be passed in as a dictionary in
    the second argument *or* as keyword parameters.
    """
    if not isinstance(tgpath, basestring):
        tgpath = "/".join(list(tgpath))
    if tgpath.startswith("/"):
        if tg_util.request_available():
            check_app_root()
            tgpath = cherrypy.request.app_root + tgpath
        result = config.get("server.webpath", "") + tgpath
    else:
        result = tgpath
    if tgparams is not None:
        tgparams.update(kw)
    else:
        tgparams = kw
    args = []
    for key, value in tgparams.iteritems():
        if value is None:
            continue
        if isinstance(value, unicode):
            value = value.encode("utf8")
        args.append("%s=%s" % (key, urllib.quote(str(value))))
    if args:
        result += "?" + "&".join(args)
    return result
Example #2
0
def url(tgpath, tgparams=None, **kw):
    """Computes URLs.

    tgpath can be a list or a string. If the path is absolute (starts
    with a "/"), the server.webpath, SCRIPT_NAME and the approot of the
    application are prepended to the path. In order for the approot to
    be detected properly, the root object should extend
    controllers.RootController.

    Query parameters for the URL can be passed in as a dictionary in
    the second argument *or* as keyword parameters.

    Values which are a list or a tuple are used to create multiple
    key-value pairs.

    """
    if not isinstance(tgpath, basestring):
        tgpath = '/'.join(list(tgpath))
    if tgpath.startswith('/'):
        webpath = (config.get('server.webpath') or '').rstrip('/')
        if tg_util.request_available():
            check_app_root()
            tgpath = request.app_root + tgpath
            try:
                webpath += request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
            except (AttributeError, KeyError):
                pass
        tgpath = webpath + tgpath
    if tgparams is None:
        tgparams = kw
    else:
        try:
            tgparams = tgparams.copy()
            tgparams.update(kw)
        except AttributeError:
            raise TypeError('url() expects a dictionary for query parameters')
    args = []
    for key, value in tgparams.iteritems():
        if value is None:
            continue
        if isinstance(value, (list, tuple)):
            pairs = [(key, v) for v in value]
        else:
            pairs = [(key, value)]
        for k, v in pairs:
            if v is None:
                continue
            if isinstance(v, unicode):
                v = v.encode('utf8')
            args.append((k, str(v)))
    if args:
        query_string = urllib.urlencode(args, True)
        if '?' in tgpath:
            tgpath += '&' + query_string
        else:
            tgpath += '?' + query_string
    return tgpath
Example #3
0
def url(tgpath, tgparams=None, **kw):
    """Computes URLs.

    tgpath can be a list or a string. If the path is absolute (starts
    with a "/"), the server.webpath, SCRIPT_NAME and the approot of the
    application are prepended to the path. In order for the approot to
    be detected properly, the root object should extend
    controllers.RootController.

    Query parameters for the URL can be passed in as a dictionary in
    the second argument *or* as keyword parameters.

    Values which are a list or a tuple are used to create multiple
    key-value pairs.

    """
    if not isinstance(tgpath, basestring):
        tgpath = '/'.join(list(tgpath))
    if tgpath.startswith('/'):
        webpath = (config.get('server.webpath') or '').rstrip('/')
        if tg_util.request_available():
            check_app_root()
            tgpath = request.app_root + tgpath
            try:
                webpath += request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
            except (AttributeError, KeyError):
                pass
        tgpath = webpath + tgpath
    if tgparams is None:
        tgparams = kw
    else:
        try:
            tgparams = tgparams.copy()
            tgparams.update(kw)
        except AttributeError:
            raise TypeError('url() expects a dictionary for query parameters')
    args = []
    for key, value in tgparams.iteritems():
        if value is None:
            continue
        if isinstance(value, (list, tuple)):
            pairs = [(key, v) for v in value]
        else:
            pairs = [(key, value)]
        for k, v in pairs:
            if v is None:
                continue
            if isinstance(v, unicode):
                v = v.encode('utf8')
            args.append((k, str(v)))
    if args:
        query_string = urllib.urlencode(args, True)
        if '?' in tgpath:
            tgpath += '&' + query_string
        else:
            tgpath += '?' + query_string
    return tgpath
Example #4
0
 def identity(self):
     try:
         id= cherrypy.request.identity
     except AttributeError:
         id= None
     if not id:
         if not request_available():
             raise RequestRequiredException()
         raise IdentityManagementNotEnabledException()
     return id
Example #5
0
 def identity(self):
     try:
         identity = cherrypy.request.identity
     except AttributeError:
         identity = None
     if not identity:
         if not request_available():
             raise RequestRequiredException()
         raise IdentityManagementNotEnabledException()
     return identity
Example #6
0
 def _cached(*args, **kw):
     if not tg_util.request_available():
         return func(*args, **kw)
     try:
         output = request._f_cache[key]
     except AttributeError:
         output = func(*args, **kw)
         request._f_cache = {key:output}
     except KeyError:
         output = request._f_cache[key] = func(*args, **kw)
     return output
Example #7
0
 def select():
     if request_available():
         result = cls.select().orderBy(order)
         if filter:
             result = result.filter(filter)
         options = [(getattr(o, id), getattr(o, title)) for o in result]
         if with_none or not options:
             options.insert(0, ('', u''))
     else:
         options = [('', u'')]
     return options
Example #8
0
def gettext(key, locale=None, domain=None):
    """Gets the gettext value for key. Added to builtins as '_'. Returns Unicode string.

    @param key: text to be translated
    @param locale: locale code to be used. If locale is None, gets the value provided by get_locale.
     """

    if request_available():
        return plain_gettext(key, locale, domain)
    else:
        return lazy_gettext(key, locale, domain)
Example #9
0
def append_to_path(widget, repetition):
    path = []
    if request_available():
        if hasattr(request, "tg_widgets_path"):
            path = request.tg_widgets_path
        else:
            request.tg_widgets_path = path
    if not path or path[-1].widget is not widget:
        path.append(Bunch(widget=widget, repetition=repetition))
        return True
    else:
        return False
Example #10
0
def append_to_path(widget, repetition):
    path = []
    if request_available():
        if hasattr(request, "tg_widgets_path"):
            path = request.tg_widgets_path
        else:
            request.tg_widgets_path = path
    if (not path) or (path[-1].widget is not widget):
        path.append(Bunch(widget=widget,
                          repetition=repetition))
        return True
    else:
        return False
Example #11
0
def ngettext(key1, key2, num, locale=None):
    """Translates two possible texts based on whether num is greater than 1.

    @param key1: text if num==1
    @param key2: text if num!=1
    @param num: a number
    @type num: integer
    @param locale: locale code to be used. If locale is None, gets the value provided by get_locale.
    """
    if request_available():
        return plain_ngettext(key1, key2, num, locale)
    else:
        return lazy_ngettext(key1, key2, num, locale)
Example #12
0
def gettext(key, locale=None, domain=None):
    """Get the gettext value for key.

    Added to builtins as '_'. Returns Unicode string.

    @param key: text to be translated
    @param locale: locale code to be used.
        If locale is None, gets the value provided by get_locale.

    """
    if request_available():
        return plain_gettext(key, locale, domain)
    else:
        return lazy_gettext(key, locale, domain)
Example #13
0
    def __getattr__(self, name):
        try:
            provider = cherrypy.request.identityProvider
        except AttributeError:
            try:
                provider = create_default_provider()
            except Exception:
                provider = None

        if provider is None:
            if not request_available():
                raise RequestRequiredException()
            raise IdentityManagementNotEnabledException()

        return getattr(provider, name)
Example #14
0
 def __getattr__(self, name):
     try:
         provider= cherrypy.request.identityProvider
     except AttributeError:
         try:
             provider = create_default_provider()
         except:
             provider= None
         
     if provider is None:
         if not request_available():
             raise RequestRequiredException()
         raise IdentityManagementNotEnabledException()
         
     return getattr(provider, name)
Example #15
0
def ngettext(key1, key2, num, locale=None):
    """Translate two possible texts based on whether num is greater than 1.

    @param key1: text if num==1
    @param key2: text if num!=1
    @param num: a number
    @type num: integer
    @param locale: locale code to be used.
        If locale is None, gets the value provided by get_locale.

    """
    if request_available():
        return plain_ngettext(key1, key2, num, locale)
    else:
        return lazy_ngettext(key1, key2, num, locale)
Example #16
0
def _get_locale():
    """Default function for returning locale. First looks in session for locale key,
    then checks the HTTP Accept-Language header, and finally checks the config default
    locale setting. This can be replaced by your own function by setting cherrypy
    config setting i18n.get_locale to your function name.
    """
    if not request_available():
        return config.get("i18n.default_locale", "en")

    if config.get("session_filter.on", False):
        locale_key = config.get("i18n.session_key", "locale")
        locale = cherrypy.session.get(locale_key)
        if locale:
            return locale
    browser_accept_lang = _get_locale_from_accept_header()
    return browser_accept_lang or config.get("i18n.default_locale", "en")
Example #17
0
def _get_locale():
    """Default function for returning locale. First looks in session for locale key,
    then checks the HTTP Accept-Language header, and finally checks the config default
    locale setting. This can be replaced by your own function by setting cherrypy
    config setting i18n.get_locale to your function name.
    """
    if not request_available():
        return config.get("i18n.default_locale", "en")

    if config.get("session_filter.on", False):
        locale_key = config.get("i18n.session_key", "locale")
        locale = cherrypy.session.get(locale_key)
        if locale:
            return locale
    browser_accept_lang = _get_locale_from_accept_header()
    return browser_accept_lang or config.get("i18n.default_locale", "en")
Example #18
0
def url(tgpath, tgparams=None, **kwargs):
    '''Computes URLs.

    This is a replacement for :func:`turbogears.controllers.url` (aka
    :func:`tg.url` in the template).  In addition to the functionality that
    :func:`tg.url` provides, it adds a token to prevent :term:`CSRF` attacks.

    :arg tgpath:  a list or a string. If the path is absolute (starts
        with a "/"), the :attr:`server.webpath`, :envvar:`SCRIPT_NAME` and
        the approot of the application are prepended to the path. In order for
        the approot to be detected properly, the root object should extend
        :class:`turbogears.controllers.RootController`.
    :kwarg tgparams: See param: ``kwargs``
    :kwarg kwargs: Query parameters for the URL can be passed in as a dictionary
        in the second argument *or* as keyword parameters.  Values which are a
        list or a tuple are used to create multiple key-value pairs.
    :returns: The changed path

    .. versionadded:: 0.3.10
       Modified from turbogears.controllers.url for :ref:`CSRF-Protection`
    '''
    if not isinstance(tgpath, basestring):
        tgpath = '/'.join(list(tgpath))
    if tgpath.startswith('/'):
        webpath = (config.get('server.webpath') or '').rstrip('/')
        if tg_util.request_available():
            check_app_root()
            tgpath = request.app_root + tgpath
            try:
                webpath += request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
            except (AttributeError, KeyError):  # pylint: disable-msg=W0704
                # :W0704: Lack of wsgi environ is fine... we still have
                # server.webpath
                pass
        tgpath = webpath + tgpath
    if tgparams is None:
        tgparams = kwargs
    else:
        try:
            tgparams = tgparams.copy()
            tgparams.update(kwargs)
        except AttributeError:
            raise TypeError(
                b_('url() expects a dictionary for query parameters'))
    args = []
    # Add the _csrf_token
    try:
        if identity.current.csrf_token:
            tgparams.update({'_csrf_token': identity.current.csrf_token})
    except RequestRequiredException:  # pylint: disable-msg=W0704
        # :W0704: If we are outside of a request (called from non-controller
        # methods/ templates) just don't set the _csrf_token.
        pass

    # Check for query params in the current url
    query_params = tgparams.iteritems()
    scheme, netloc, path, params, query_s, fragment = urlparse.urlparse(tgpath)
    if query_s:
        query_params = chain(
            (p for p in cgi.parse_qsl(query_s) if p[0] != '_csrf_token'),
            query_params)

    for key, value in query_params:
        if value is None:
            continue
        if isinstance(value, (list, tuple)):
            pairs = [(key, v) for v in value]
        else:
            pairs = [(key, value)]
        for key, value in pairs:
            if value is None:
                continue
            if isinstance(value, unicode):
                value = value.encode('utf8')
            args.append((key, str(value)))
    query_string = urllib.urlencode(args, True)
    tgpath = urlparse.urlunparse(
        (scheme, netloc, path, params, query_string, fragment))
    return tgpath
Example #19
0
def pop_from_path():
    if request_available() and hasattr(request, "tg_widgets_path"):
        request.tg_widgets_path.pop()
Example #20
0
def url(tgpath, tgparams=None, **kwargs):
    '''Computes URLs.

    This is a replacement for :func:`turbogears.controllers.url` (aka
    :func:`tg.url` in the template).  In addition to the functionality that
    :func:`tg.url` provides, it adds a token to prevent :term:`CSRF` attacks.

    :arg tgpath:  a list or a string. If the path is absolute (starts
        with a "/"), the :attr:`server.webpath`, :envvar:`SCRIPT_NAME` and
        the approot of the application are prepended to the path. In order for
        the approot to be detected properly, the root object should extend
        :class:`turbogears.controllers.RootController`.
    :kwarg tgparams: See param: ``kwargs``
    :kwarg kwargs: Query parameters for the URL can be passed in as a
        dictionary in the second argument *or* as keyword parameters.
        Values which are a list or a tuple are used to create multiple
        key-value pairs.
    :returns: The changed path

    .. versionadded:: 0.3.10
       Modified from turbogears.controllers.url for :ref:`CSRF-Protection`
    '''
    if not isinstance(tgpath, basestring):
        tgpath = '/'.join(list(tgpath))
    if tgpath.startswith('/'):
        webpath = (config.get('server.webpath') or '').rstrip('/')
        if tg_util.request_available():
            check_app_root()
            tgpath = request.app_root + tgpath
            try:
                webpath += request.wsgi_environ['SCRIPT_NAME'].rstrip('/')
            except (AttributeError, KeyError):  # pylint: disable-msg=W0704
                # :W0704: Lack of wsgi environ is fine... we still have
                # server.webpath
                pass
        tgpath = webpath + tgpath
    if tgparams is None:
        tgparams = kwargs
    else:
        try:
            tgparams = tgparams.copy()
            tgparams.update(kwargs)
        except AttributeError:
            raise TypeError(
                'url() expects a dictionary for query parameters')
    args = []
    # Add the _csrf_token
    try:
        if identity.current.csrf_token:
            tgparams.update({'_csrf_token': identity.current.csrf_token})
    except RequestRequiredException:  # pylint: disable-msg=W0704
        # :W0704: If we are outside of a request (called from non-controller
        # methods/ templates) just don't set the _csrf_token.
        pass

    # Check for query params in the current url
    query_params = tgparams.iteritems()
    scheme, netloc, path, params, query_s, fragment = urlparse.urlparse(tgpath)
    if query_s:
        query_params = chain((p for p in cgi.parse_qsl(query_s) if p[0] !=
                              '_csrf_token'), query_params)

    for key, value in query_params:
        if value is None:
            continue
        if isinstance(value, (list, tuple)):
            pairs = [(key, v) for v in value]
        else:
            pairs = [(key, value)]
        for key, value in pairs:
            if value is None:
                continue
            if isinstance(value, unicode):
                value = value.encode('utf8')
            args.append((key, str(value)))
    query_string = urllib.urlencode(args, True)
    tgpath = urlparse.urlunparse((scheme, netloc, path, params, query_string,
                                  fragment))
    return tgpath
Example #21
0
    def display(self, value=None, **params):
        """Display the widget in a Kid template.

        Returns an elementtree node instance. If you need serialized output
        in a string, call 'render' instead.

        Probably you will not need to override or extend if inheriting from
        Widget.

        @params:

        value   : The value to display in the widget.
        **params: Extra parameters specific to the widget. All keyword params
                  supplied will pass through the update_params method which
                  will have a last chance to modify them before reaching the
                  template.

        """
        if not getattr(self, 'template_c', False):
            warnings.warn('kid' in view.engines
                and "Widget instance %r has no template defined" % self
                or "Trying to render a widget, but the Kid"
                    " templating engine is not installed or not yet loaded.")
            return None

        # logic for managing the params attribute
        for param in self.__class__.params:
            if param in params:
                param_value = params[param]
                if callable(param_value):
                    param_value = param_value()

            else:
                # if the param hasn't been overridden (passed as a keyword
                # argument inside **params) put the corresponding instance
                # value inside params.
                param_value = getattr(self, param, None)

            # make sure we don't pass a reference to mutables
            params[param] = copy_if_mutable(param_value)

        if not params.get('name'):
            params['name'] = self.name

        if value is None:
            value = self.default
            if callable(value):
                value = value()
        params['value'] = to_unicode(self.adjust_value(value, **params))

        self.update_params(params)

        try:
            transform = view.engines['kid'].transform
        except (KeyError, AttributeError):
            # this can happen if you render a widget before application startup
            # when view.load_engines() has not yet been called
            raise RuntimeError("Trying to render a widget, but the Kid"
                " templating engine is not installed or not yet loaded.")

        # If the page template is Genshi, we keep track of the nesting level,
        # because Genshi cannot display Kid's ElementTree elements directly.
        if request_available() and request.tg_template_enginename == 'genshi':
            display_level = getattr(request, 'tg_widgets_display_level', 0)
            request.tg_widgets_display_level = display_level + 1
        else:
            display_level = None

        try:
            output = transform(params, self.template_c)
            if display_level == 0:
                # On the topmost level, we create a Genshi markup stream
                # from Kid's ElementTree element to make Genshi really happy.
                # This automatism makes wrapping widget output with ET(...)
                # calls in Genshi page templates unnecessary.
                output = view.genshi_et(output)
        finally:
            if display_level is not None:
                request.tg_widgets_display_level = display_level

        return output
 def test_url_without_request_available(self):
     #Stopping the server in tearDown ensures that there's no request
     assert not util.request_available()
     assert url("/foo") == "/foo"
Example #23
0
def pop_from_path():
    if request_available() and hasattr(request, "tg_widgets_path"):
        request.tg_widgets_path.pop()