예제 #1
0
    def __init__(self):
        super(LdapSqlAlchemyIdentityProvider, self).__init__()

        global user_class, group_class, permission_class, visit_class

        self.ldap = get("identity.ldap.enabled", False)
        if self.ldap:
            self.uri = get("identity.soldapprovider.uri", "ldaps://localhost")
            self.basedn  = get("identity.soldapprovider.basedn", "dc=localhost")
            self.autocreate = get("identity.soldapprovider.autocreate", False)
            # Only needed for devel. comment out for Prod.
            ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
            log.info("uri :: %s" % self.uri)
            log.info("basedn :: %s" % self.basedn)
            log.info("autocreate :: %s" % self.autocreate)

        user_class_path = get("identity.saprovider.model.user",
                              None)
        user_class = load_class(user_class_path)
        group_class_path = get("identity.saprovider.model.group",
                                None)
        group_class = load_class(group_class_path)
        permission_class_path = get("identity.saprovider.model.permission",
                                    None)
        permission_class = load_class(permission_class_path)
        visit_class_path = get("identity.saprovider.model.visit",
                               None)
        log.info("Loading: %s", visit_class_path)
        visit_class = load_class(visit_class_path)
예제 #2
0
파일: safasprovider.py 프로젝트: Affix/fas
    def __init__(self):
        super(SaFasIdentityProvider, self).__init__()

        global user_class
        global visit_class

        user_class_path = config.get("identity.saprovider.model.user", None)
        user_class = load_class(user_class_path)
        visit_class_path = config.get("identity.saprovider.model.visit", None)
        log.info(_("Loading: %(visitmod)s") % \
                {'visitmod': visit_class_path})
        visit_class = load_class(visit_class_path)
예제 #3
0
    def __init__(self):
        super(SaFasIdentityProvider, self).__init__()

        global user_class
        global visit_class

        user_class_path = config.get("identity.saprovider.model.user", None)
        user_class = load_class(user_class_path)
        visit_class_path = config.get("identity.saprovider.model.visit", None)
        log.info(_("Loading: %(visitmod)s") % \
                {'visitmod': visit_class_path})
        visit_class = load_class(visit_class_path)
예제 #4
0
 def __init__(self, timeout):
     global visit_class
     super(DejavuVisitManager,self).__init__( timeout )
     visit_class_path = config.get("visit.djprovider.model", __name__ + ".TG_Visit")
     visit_class = load_class(visit_class_path)
     if visit_class:
         log.info("Succesfully loaded \"%s\"" % visit_class_path)
예제 #5
0
def create_default_provider():
    """Create default identity provider.

    Creates an identity provider according to what is found in
    the configuration file for the current TurboGears application

    Returns an identity provider instance or
    raises an IdentityConfigurationException.

    """
    provider_plugin = turbogears.config.get('identity.provider', 'sqlobject')
    plugins = pkg_resources.iter_entry_points(
        'turbogears.identity.provider', provider_plugin)

    log.debug("Loading provider from plugin: %s", provider_plugin)

    provider_class = None
    for entrypoint in plugins:
        provider_class = entrypoint.load()
        break

    if not provider_class:
        provider_class = load_class(provider_plugin)

    if not provider_class:
        raise IdentityConfigurationException(
            "IdentityProvider plugin missing: %s" % provider_plugin )
    else:
        return provider_class()
예제 #6
0
def create_default_provider():
    """Create default identity provider.

    Creates an identity provider according to what is found in
    the configuration file for the current TurboGears application

    Returns an identity provider instance or
    raises an IdentityConfigurationException.

    """
    provider_plugin = turbogears.config.get('identity.provider', 'sqlobject')
    plugins = pkg_resources.iter_entry_points(
        'turbogears.identity.provider', provider_plugin)

    log.debug("Loading provider from plugin: %s", provider_plugin)

    provider_class = None
    for entrypoint in plugins:
        provider_class = entrypoint.load()
        break

    if not provider_class:
        provider_class = load_class(provider_plugin)

    if not provider_class:
        raise IdentityConfigurationException(
            "IdentityProvider plugin missing: %s" % provider_plugin )
    else:
        return provider_class()
예제 #7
0
파일: sovisit.py 프로젝트: thraxil/gtreed
 def __init__(self, timeout):
     global visit_class
     visit_class_path = config.get("visit.soprovider.model", 
         "turbogears.visit.sovisit.TG_Visit")
     visit_class = load_class(visit_class_path)
     if visit_class:
         log.info("Succesfully loaded \"%s\"" % visit_class_path)
     super(SqlObjectVisitManager,self).__init__( timeout )
예제 #8
0
 def __init__(self, timeout):
     global visit_class
     super(DejavuVisitManager, self).__init__(timeout)
     visit_class_path = config.get("visit.djprovider.model",
                                   __name__ + ".TG_Visit")
     visit_class = load_class(visit_class_path)
     if visit_class:
         log.info("Succesfully loaded \"%s\"" % visit_class_path)
예제 #9
0
파일: savisit.py 프로젝트: thraxil/gtreed
 def __init__(self, timeout):
     global visit_class
     super(SqlAlchemyVisitManager,self).__init__(timeout)
     visit_class_path = config.get("visit.saprovider.model",
                            "turbogears.visit.savisit.TG_Visit")
     visit_class = load_class(visit_class_path)
     bind_meta_data()
     if visit_class is TG_Visit:
         assign_mapper(session.context, visit_class, visits_table)
예제 #10
0
 def __init__(self, timeout):
     global visit_class
     visit_class_path = config.get("visit.soprovider.model",
                                   "turbogears.visit.sovisit.TG_Visit")
     visit_class = load_class(visit_class_path)
     if visit_class:
         log.info("Successfully loaded \"%s\"" % visit_class_path)
     # base-class' __init__ triggers self.create_model, so mappers need to
     # be initialized before.
     super(SqlObjectVisitManager, self).__init__(timeout)
예제 #11
0
파일: sovisit.py 프로젝트: bmoar/turbogears
 def __init__(self, timeout):
     global visit_class
     visit_class_path = config.get("visit.soprovider.model",
         "turbogears.visit.sovisit.TG_Visit")
     visit_class = load_class(visit_class_path)
     if visit_class:
         log.info("Successfully loaded \"%s\"" % visit_class_path)
     # base-class' __init__ triggers self.create_model, so mappers need to
     # be initialized before.
     super(SqlObjectVisitManager, self).__init__(timeout)
예제 #12
0
    def __init__(self):
        super(SqlAlchemyIdentityProvider, self).__init__()
        get = config.get

        global user_class, group_class, permission_class, visit_class

        user_class_path = get("identity.saprovider.model.user", None)
        user_class = load_class(user_class_path)
        group_class_path = get("identity.saprovider.model.group", None)
        group_class = load_class(group_class_path)
        permission_class_path = get("identity.saprovider.model.permission",
                                    None)
        permission_class = load_class(permission_class_path)
        visit_class_path = get("identity.saprovider.model.visit", None)
        log.info("Loading: %s", visit_class_path)
        visit_class = load_class(visit_class_path)
        # Default encryption algorithm is to use plain text passwords
        algorithm = get("identity.saprovider.encryption_algorithm", None)
        self.encrypt_password = lambda pw: \
            identity._encrypt_password(algorithm, pw)
예제 #13
0
    def __init__(self):
        super(SqlAlchemyIdentityProvider, self).__init__()
        get = config.get

        global user_class, group_class, permission_class, visit_class

        user_class_path = get("identity.saprovider.model.user", None)
        user_class = load_class(user_class_path)
        group_class_path = get("identity.saprovider.model.group", None)
        group_class = load_class(group_class_path)
        permission_class_path = get(
            "identity.saprovider.model.permission", None)
        permission_class = load_class(permission_class_path)
        visit_class_path = get("identity.saprovider.model.visit", None)
        log.info("Loading: %s", visit_class_path)
        visit_class = load_class(visit_class_path)
        # Default encryption algorithm is to use plain text passwords
        algorithm = get("identity.saprovider.encryption_algorithm", None)
        self.encrypt_password = lambda pw: \
            identity._encrypt_password(algorithm, pw)
예제 #14
0
 def __init__(self):
     super(SqlObjectIdentityProvider, self).__init__()
     get=turbogears.config.get
     
     global user_class, group_class, permission_class, visit_class
     
     user_class_path= get( "identity.soprovider.model.user", 
                           __name__ + ".TG_User" )
     #log.debug('userclassp:%s'% user_class_path)
     #user_class_path = 'kronos.model.Person'
     user_class= load_class(user_class_path)
     if user_class:
         log.info("Succesfully loaded \"%s\"" % user_class_path)
     try:
         self.user_class_db_encoding= \
             user_class.sqlmeta.columns['user_name'].dbEncoding
     except (KeyError, AttributeError):
         self.user_class_db_encoding= 'UTF-8'
     group_class_path= get( "identity.soprovider.model.group",
                             __name__ + ".TG_Group" )
     group_class= load_class(group_class_path)
     if group_class:
         log.info("Succesfully loaded \"%s\"" % group_class_path)
         
     permission_class_path= get( "identity.soprovider.model.permission",
                                 __name__ + ".TG_Permission" )
     permission_class= load_class(permission_class_path)
     if permission_class:
         log.info("Succesfully loaded \"%s\"" % permission_class_path)
     
     visit_class_path= get( "identity.soprovider.model.visit",
                             __name__ + ".TG_VisitIdentity" )
     visit_class= load_class(visit_class_path)
     if visit_class:
         log.info("Succesfully loaded \"%s\"" % visit_class_path)
     
         
     # Default encryption algorithm is to use plain text passwords
     algorithm = get("identity.soprovider.encryption_algorithm", None)
     self.encrypt_password = lambda pw: \
                                 identity._encrypt_password(algorithm, pw)
예제 #15
0
def _process_output(engine, output, template, format):
    """Produces final output form from the data returned from a
    controller method.

    @param tg_format: format of desired output (html or json)
    @param output: the output returned by the controller
    @param template: HTML template to use
    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for i in include_widgets_lst:
            widget = tg_util.load_class(i)
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        #output.update([("tg_js_%s" % str(l), js[l]) for l in js_location])
        for l in iter(js_location):
            output["tg_js_%s" % str(l)] = js[l]

        output["tg_flash"] = output.get("tg_flash")

        return engine.render(output, format=format, template=template)
예제 #16
0
 def __init__(self):
     global session_class
     session_class_path = turbogears.config.get("session_filter.storage_table", __name__ + ".TG_Session")
     session_class = load_class(session_class_path)
     arena = hub.getConnection().arena
     try:
         if not arena._registered_classes.has_key( session_class ):
             arena.register( session_class )
             if not arena.has_storage( session_class ):
                 arena.create_storage( session_class )
     except Exception, e:
         log.info( str( e ) )
예제 #17
0
 def __init__(self):
     global session_class
     session_class_path = turbogears.config.get(
         "session_filter.storage_table", __name__ + ".TG_Session")
     session_class = load_class(session_class_path)
     arena = hub.getConnection().arena
     try:
         if not arena._registered_classes.has_key(session_class):
             arena.register(session_class)
             if not arena.has_storage(session_class):
                 arena.create_storage(session_class)
     except Exception, e:
         log.info(str(e))
예제 #18
0
    def __init__(self):
        super(SqlObjectCsrfIdentityProvider, self).__init__()
        get = turbogears.config.get

        global user_class, group_class, permission_class, visit_class

        user_class_path = get("identity.soprovider.model.user",
                              __name__ + ".TG_User")
        user_class = load_class(user_class_path)
        if user_class:
            log.info("Succesfully loaded \"%s\"" % user_class_path)
        try:
            self.user_class_db_encoding = \
                user_class.sqlmeta.columns['user_name'].dbEncoding or 'UTF-8'
        except (KeyError, AttributeError):
            self.user_class_db_encoding = 'UTF-8'
        group_class_path = get("identity.soprovider.model.group",
                               __name__ + ".TG_Group")
        group_class = load_class(group_class_path)
        if group_class:
            log.info("Succesfully loaded \"%s\"" % group_class_path)

        permission_class_path = get("identity.soprovider.model.permission",
                                    __name__ + ".TG_Permission")
        permission_class = load_class(permission_class_path)
        if permission_class:
            log.info("Succesfully loaded \"%s\"" % permission_class_path)

        visit_class_path = get("identity.soprovider.model.visit",
                               __name__ + ".TG_VisitIdentity")
        visit_class = load_class(visit_class_path)
        if visit_class:
            log.info("Succesfully loaded \"%s\"" % visit_class_path)

        # Default encryption algorithm is to use plain text passwords
        algorithm = get("identity.soprovider.encryption_algorithm", None)
        self.encrypt_password = lambda pw: \
            identity._encrypt_password(algorithm, pw)
예제 #19
0
    def __init__(self):
        super(Distro, self).__init__()
        glob_ns = globals()


        classname = 'Base'
        class_path = config.get('mirrormanager.distro', classname)
        class_ = load_class(class_path)
        if class_:
            log.info('Successfully loaded "%s".', class_path)
            glob_ns['%s_class' % classname] = class_
        else:
            log.error('Could not load class "%s".'
                      ' Check mirrormanager.distro setting')
예제 #20
0
    def __init__(self, timeout):
        global visit_class
        visit_class_path = config.get("visit.saprovider.model", "turbogears.visit.savisit.TG_Visit")
        visit_class = load_class(visit_class_path)
        if visit_class is None:
            msg = "No visit class found for %s" % visit_class_path
            msg += ", did you run setup.py develop?"
            log.error(msg)

        get_engine()
        if visit_class is TG_Visit:
            mapper(visit_class, visits_table)
        # base-class' __init__ triggers self.create_model, so mappers need to
        # be initialized before.
        super(SqlAlchemyVisitManager, self).__init__(timeout)
예제 #21
0
    def __init__(self, timeout):
        global visit_class
        visit_class_path = config.get("visit.saprovider.model",
            "turbogears.visit.savisit.TG_Visit")
        visit_class = load_class(visit_class_path)
        if visit_class is None:
            msg = 'No visit class found for %s' % visit_class_path
            msg += ', did you run setup.py develop?'
            log.error(msg)

        get_engine()
        if visit_class is TG_Visit:
            mapper(visit_class, visits_table)
        # base-class' __init__ triggers self.create_model, so mappers need to
        # be initialized before.
        super(SqlAlchemyVisitManager, self).__init__(timeout)
예제 #22
0
    def __init__(self):
        super(SqlAlchemyIdentityProvider, self).__init__()
        glob_ns = globals()

        for classname in ('user', 'group', 'permission', 'visit'):
            default_classname = '.TG_' + (classname == 'visit'
                and 'VisitIdentity' or classname.capitalize())
            class_path = config.get("identity.saprovider.model.%s" % classname,
                __name__ + default_classname)
            class_ = load_class(class_path)
            if class_:
                log.info('Successfully loaded "%s".', class_path)
                glob_ns['%s_class' % classname] = class_
            else:
                log.error('Could not load class "%s". Check '
                    'identity.saprovider.model.%s setting', class_path, classname)
예제 #23
0
    def __init__(self):
        super(SqlObjectIdentityProvider, self).__init__()
        glob_ns = globals()

        for classname in ('user', 'group', 'permission', 'visit'):
            default_classname = '.TG_' + (classname == 'visit'
                and 'VisitIdentity' or classname.capitalize())
            class_path = config.get("identity.soprovider.model.%s" % classname,
                __name__ + default_classname)
            class_ = load_class(class_path)
            if class_:
                log.info('Successfully loaded "%s".', class_path)
                glob_ns['%s_class' % classname] = class_
            else:
                log.error('Could not load class "%s". Check '
                    'identity.soprovider.model.%s setting', class_path, classname)
        try:
            self.user_class_db_encoding = \
                glob_ns['user_class'].sqlmeta.columns['user_name'].dbEncoding
        except (KeyError, AttributeError):
            self.user_class_db_encoding = 'UTF-8'
        if not self.user_class_db_encoding: self.user_class_db_encoding = 'UTF-8' 
예제 #24
0
    def __init__(self, timeout):
        global visit_class
        visit_class_path = config.get("visit.saprovider.model",
            "turbogears.visit.savisit.TG_Visit")
        visit_class = load_class(visit_class_path)
        if visit_class is None:
            msg = 'No visit class found for %s' % visit_class_path
            msg += ', did you run setup.py develop?'
            log.error(msg)
        else:
            log.info('Successfully loaded "%s"', visit_class_path)

        if visit_class is TG_Visit:
            # Handle it gracefully when TG_Visit is already mapped.
            # May happen, when the visit manager is shutdown and started again
            try:
                class_mapper(visit_class)
            except UnmappedClassError:
                mapper(visit_class, visits_table)
        # base-class' __init__ triggers self.create_model, so mappers need to
        # be initialized before.
        super(SqlAlchemyVisitManager, self).__init__(timeout)
예제 #25
0
def _process_output(output,
                    template,
                    format,
                    content_type,
                    mapping,
                    fragment=False):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for i in include_widgets_lst:
            widget = tg_util.load_class(i)
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        for location in iter(js_location):
            output["tg_js_%s" % str(location)] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output["tg_flash"] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output,
                             template=template,
                             format=format,
                             mapping=mapping,
                             headers=headers,
                             fragment=fragment)
        content_type = headers['Content-Type']

    if content_type:
        response.headers["Content-Type"] = content_type
    else:
        content_type = response.headers.get("Content-Type", 'text/plain')

    if content_type.startswith("text/"):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
예제 #26
0
def _process_output(output, template, format, content_type, mapping, fragment=False):
    """Produces final output form from the data returned from a
    controller method.

    @param tg_format: format of desired output (html or json)
    @param output: the output returned by the controller
    @param template: HTML template to use
    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')
            
        for i in include_widgets_lst:
            widget = tg_util.load_class(i)  
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        #output.update([("tg_js_%s" % str(l), js[l]) for l in js_location])
        for l in iter(js_location):
            output["tg_js_%s" % str(l)] = js[l]

        tg_flash = _get_flash() 
        if not tg_flash == None:
            output["tg_flash"] = tg_flash 
        output = view.render(output, template=template, format=format,
                    mapping=mapping, content_type=content_type,
                    fragment=fragment)
    else:
        if content_type:
            cherrypy.response.headers["Content-Type"] = content_type

    # fix the Safari XMLHttpRequest encoding problem
    try:
        contentType = cherrypy.response.headers["Content-Type"]
        ua = cherrypy.request.headers["User-Agent"]
    except KeyError:
        return output
    if not contentType.startswith("text/"):
        return output
    ua = view.UserAgent(ua)
    enc = tg_util.get_template_encoding_default()
    if ua.browser == "safari":
        if isinstance(output, str):
            output = output.decode(enc)
        output = unicodechars.sub(
            lambda m: "&#x%x;" % ord(m.group(1)), output).encode("ascii")
    if isinstance(output, unicode):
        output = output.encode(enc)
    return output
예제 #27
0
def _process_output(output, template, format, content_type, fragment=False,
                    **options):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        # import this here to prevent circular import in widgets.forms
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get('tg.include_widgets', [])

        if config.get('tg.mochikit_all', False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for name in include_widgets_lst:
            widget = tg_util.load_class(name)
            if widget is None:
                log.debug("Could not load widget %s", name)
                continue
            if isclass(widget):
                widget = widget()
            if hasattr(widget, 'retrieve_resources') and hasattr(widget, 'inject'):
                # it's a ToscaWidget, we register it for injection
                widget.inject()
            # XXX: widgets with same base name will override each other
            include_widgets['tg_%s' % name.rsplit('.', 1)[-1]] = widget
        output.update(include_widgets)

        # collect JS/CSS resources from widgets in the output dict or
        # tg.include_widgets
        for value in output.itervalues():
            if hasattr(value, 'retrieve_resources'):
                # it's a ToscaWidget, will be injected by the ToscaWidget middleware
                continue
            else:
                try:
                    css_resources = value.retrieve_css()
                except (AttributeError, TypeError):
                    css_resources = []
                try:
                    js_resources = value.retrieve_javascript()
                except (AttributeError, TypeError):
                    js_resources = []
            css.add_all(css_resources)
            for script in js_resources:
                location = getattr(script, 'location', js_location.head)
                js[location].add(script)
        css.sort(key=lambda obj:  getattr(obj, 'order', 0))
        output['tg_css'] = css
        for location in iter(js_location):
            js[location].sort(key=lambda obj:  getattr(obj, 'order', 0))
            output['tg_js_%s' % location] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output['tg_flash'] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output, template=template, format=format,
                             headers=headers, fragment=fragment, **options)
        content_type = headers['Content-Type']

    if content_type:
        response.headers['Content-Type'] = content_type
    else:
        content_type = response.headers.get('Content-Type', 'text/plain')

    if content_type.startswith('text/'):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
예제 #28
0
def _process_output(output, template, format, content_type,
        mapping, fragment=False):
    """Produce final output form from data returned from a controller method.

    See the expose() arguments for more info since they are the same.

    """
    if isinstance(output, dict):
        from turbogears.widgets import js_location

        css = tg_util.setlike()
        js = dict(izip(js_location, iter(tg_util.setlike, None)))
        include_widgets = {}
        include_widgets_lst = config.get("tg.include_widgets", [])

        if config.get("tg.mochikit_all", False):
            include_widgets_lst.insert(0, 'turbogears.mochikit')

        for i in include_widgets_lst:
            widget = tg_util.load_class(i)
            if isclass(widget):
                widget = widget()
            include_widgets["tg_%s" % i.split(".")[-1]] = widget
            for script in widget.retrieve_javascript():
                if hasattr(script, "location"):
                    js[script.location].add(script)
                else:
                    js[js_location.head].add(script)
            css.add_all(widget.retrieve_css())

        for value in output.itervalues():
            if hasattr(value, "retrieve_css"):
                retrieve = getattr(value, "retrieve_css")
                if callable(retrieve):
                    css.add_all(value.retrieve_css())
            if hasattr(value, "retrieve_javascript"):
                retrieve = getattr(value, "retrieve_javascript")
                if callable(retrieve):
                    for script in value.retrieve_javascript():
                        if hasattr(script, "location"):
                            js[script.location].add(script)
                        else:
                            js[js_location.head].add(script)
        output.update(include_widgets)
        output["tg_css"] = css
        for location in iter(js_location):
            output["tg_js_%s" % str(location)] = js[location]

        tg_flash = _get_flash()
        if tg_flash:
            output["tg_flash"] = tg_flash

        headers = {'Content-Type': content_type}
        output = view.render(output, template=template, format=format,
                    mapping=mapping, headers=headers,
                    fragment=fragment)
        content_type = headers['Content-Type']

    if content_type:
        response.headers["Content-Type"] = content_type
    else:
        content_type = response.headers.get("Content-Type", 'text/plain')

    if content_type.startswith("text/"):
        if isinstance(output, unicode):
            output = output.encode(tg_util.get_template_encoding_default())

    return output
예제 #29
0
    """Create a VisitManager based on the plugin specified in the config file."""
    plugin_name = config.get("visit.manager", "sqlalchemy")
    plugins = pkg_resources.iter_entry_points(
        "turbogears.visit.manager", plugin_name)
    log.debug("Loading visit manager from plugin: %s", plugin_name)
    provider_class = None
    for entrypoint in plugins:
        try:
            provider_class = entrypoint.load()
            break
        except ImportError, e:
            log.error("Error loading visit plugin '%s': %s", entrypoint, e)

    if not provider_class and '.' in plugin_name:
        try:
            provider_class = load_class(plugin_name)
        except ImportError, e:
            log.error("Error loading visit class '%s': %s", plugin_name, e)
    if not provider_class:
        raise RuntimeError("VisitManager plugin missing: %s" % plugin_name)
    return provider_class(timeout)


# Interface for the TurboGears extension

def start_extension():
    global _manager

    # Bail out if the application hasn't enabled this extension
    if not config.get("visit.on", False):
        return