当前位置: 首页>>代码示例>>Python>>正文


Python controllers.WSGIController类代码示例

本文整理汇总了Python中pylons.controllers.WSGIController的典型用法代码示例。如果您正苦于以下问题:Python WSGIController类的具体用法?Python WSGIController怎么用?Python WSGIController使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了WSGIController类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        controller = environ['pylons.routes_dict']['controller']

        if controller == 'template':
            return WSGIController.__call__(self, environ, start_response)
        username = environ.get('REMOTE_USER')
        if not username and controller != 'config':
            return WSGIResponse(content='please log in', code=401)

        if environ.get('AUTHENTICATION_METHOD') != 'WSSE':
            if controller == 'watch' or controller == 'user':
                c.user = User.get_or_create(username)
            else:
                if (environ.get('REMOTE_ADDR').startswith('127.0.0.1') and controller == 'config') or controller == 'error':
                    #local users can configure Twirlip and see errors
                    pass
                else:
                    #all other authentication must be by wsse
                    return WSGIResponse(code=403, content='You need to authenticate with wsse to access %s ' % controller)
            
        if controller == 'page':
            #json
            self.params = {}
            for param, value in request.params.items():
                self.params[param] = loads(value)
                    
        return WSGIController.__call__(self, environ, start_response)
开发者ID:socialplanning,项目名称:Twirlip,代码行数:32,代码来源:base.py

示例2: __init__

 def __init__(self):
     WSGIController.__init__(self)
     self.cert_dn = None
     self.cert_vo = None
     self.cert_fqans = []
     self.fqans_string = ''
     self.cert_owner = None
开发者ID:grid4hpc,项目名称:pilot,代码行数:7,代码来源:base.py

示例3: __init__

    def __init__(self, *args, **kwargs):
        """Implements TG2 style controller-level permissions requirements.

        If the allow_only class attribute has been set, wrap the __before__
        method with an ActionProtector using the predicate defined there.
        """
        if hasattr(self, 'allow_only') \
        and isinstance(self.allow_only, Predicate):
            # ControllerProtector wraps the __before__ method of this instance.
            cp = ControllerProtector(self.allow_only)
            self = cp(self)
        WSGIController.__init__(self, *args, **kwargs)
开发者ID:Jpoudrier,项目名称:mediacore-community,代码行数:12,代码来源:base.py

示例4: __init__

 def __init__(self, provider, controller, *args, **kwargs):
     self.provider = provider
     self.sprockets = Sprockets(provider, controller)
     self.controller = controller
     #commonly used views
     c.w = WidgetBunch()
     sprocket = self.sprockets['databaseView']
     self.databaseValue = sprocket.session.getValue()
     self.databaseView  = sprocket.view.widget
     print 'controller:', self.controller
     
     self.databaseDict  = dict(controller=self.controller)
     self.genshi_loader = TemplateLoader([pkg_resources.resource_filename('dbsprockets.dbmechanic.frameworks.pylons', 'templates')])
     WSGIController.__init__(self, *args, **kwargs)
开发者ID:arianepaola,项目名称:tg2jython,代码行数:14,代码来源:dbmechanic.py

示例5: __call__

    def __call__(self, environ, start_response):
        # we override this here to ensure that this header, and only this
        # header, is trusted to reduce the number of potential
        # misconfigurations between wsgi application servers (e.g. gunicorn
        # which trusts three different headers out of the box for this) and
        # haproxy (which won't clean out bad headers by default)
        forwarded_proto = environ.get("HTTP_X_FORWARDED_PROTO", "http").lower()
        assert forwarded_proto in ("http", "https")
        request.environ["wsgi.url_scheme"] = forwarded_proto

        forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', ())
        remote_addr = environ.get('REMOTE_ADDR')

        request.via_cdn = False
        cdn_ip = g.cdn_provider.get_client_ip(environ)
        if cdn_ip:
            request.ip = cdn_ip
            request.via_cdn = True
        elif g.trust_local_proxies and forwarded_for and is_local_address(remote_addr):
            request.ip = forwarded_for.split(',')[-1]
        else:
            request.ip = environ['REMOTE_ADDR']

        #if x-dont-decode is set, pylons won't unicode all the parameters
        if environ.get('HTTP_X_DONT_DECODE'):
            request.charset = None

        request.referer = environ.get('HTTP_REFERER')
        request.user_agent = environ.get('HTTP_USER_AGENT')
        request.fullpath = environ.get('FULLPATH', request.path)
        request.fullurl = request.host_url + request.fullpath
        request.port = environ.get('request_port')
        
        if_modified_since = environ.get('HTTP_IF_MODIFIED_SINCE')
        if if_modified_since:
            request.if_modified_since = read_http_date(if_modified_since)
        else:
            request.if_modified_since = None

        #set the function to be called
        action = request.environ['pylons.routes_dict'].get('action')

        if (request.environ.get('r2.controller.exception') and action == 'document'
                and request.environ.get('render_style') == 'api'):
            action = 'api_error'
        if action:
            meth = request.method.upper()
            if meth == 'HEAD':
                meth = 'GET'

            if (meth == 'OPTIONS' and
                    self._get_action_handler(action, meth) is None):
                handler_name = meth
            else:
                handler_name = meth + '_' + action

            request.environ['pylons.routes_dict']['action_name'] = action
            request.environ['pylons.routes_dict']['action'] = handler_name

        return WSGIController.__call__(self, environ, start_response)
开发者ID:khodges42,项目名称:reddit,代码行数:60,代码来源:base.py

示例6: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        environ = request.environ
        controller = environ['pylons.routes_dict'].get('controller')
        if request.method == "POST" and controller != "auth" and controller != "hookbox" and controller != 'error':
            params = request.params
            submitted_token = params.get(secure_form.token_key)
            if submitted_token != secure_form.authentication_token():
                #raise RuntimeError("Not secure")
                pass #FIXME: uncomment above

        user_id = session.get("user_id")
        if user_id:
            c.user = self.user = User.get(user_id)
            if not self.user.is_logged_in():
                del session["user_id"]
                c.user = self.user = None
        else:
            c.user = self.user = None


        #generate hookbox server url
        hookbox_server = url('/', qualified=True)
        parsed = urlparse(hookbox_server)
        #a really fancy way of saying host:8001
        c.hookbox_server = parsed.scheme + "://" + parsed.hostname + ":" + config["hookbox_js_port"]

        return WSGIController.__call__(self, environ, start_response)
开发者ID:novalis,项目名称:Anagrams,代码行数:32,代码来源:base.py

示例7: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        tmpl_context.current_navtab = 'blah'
        tmpl_context.current_subnavtab = 'blakj'
        tmpl_context.status = 1
        tmpl_context.messagebar_text = ''
        tmpl_context.message = ''
        tmpl_context.username = ''

        beaker = environ.get('beaker.session') or {}
        try:
            timeout = int(config.get('cw.timeout'))
        except Exception:
            timeout = 0
        if timeout and beaker.get('user_id'):
            last_access = beaker.get('last_accessed') or False
            if last_access and datetime.now() - last_access > timedelta(minutes=timeout):
                try:
                    return "Your session has timed out. You have been logged out for security."
                finally:
                    Session.remove()
            beaker['last_accessed'] = datetime.now()
            beaker.save()

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            Session.remove()
开发者ID:sumukh210991,项目名称:Cyberweb,代码行数:31,代码来源:base.py

示例8: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller."""
        # set the language fallback to english
        add_fallback("en")
        # define the language based on browser preference
        user_agent_language = request.languages[0][0:2]
        set_lang(user_agent_language)
        formencode.api.set_stdtranslation(user_agent_language)

        # common values mostly inherited from config file
        c.version = __version__ # TODO move this into the development.ini file
        c.site_full_name = config["site_full_name"] # TODO move this into the development.ini file
        c.site_short_name = config["site_short_name"] # TODO move this into the development.ini file

        # controler and action named for use in templates
        #c.controller = request.environ['pylons.routes_dict']['controller']
        #c.action = request.environ['pylons.routes_dict']['action']

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            meta.Session.remove()
开发者ID:lazaret,项目名称:archeobases,代码行数:25,代码来源:base.py

示例9: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Clean out any old cookies as they may contain api keys etc
        # This also improves the cachability of our pages as cookies
        # prevent proxy servers from caching content unless they have
        # been configured to ignore them.
        for cookie in request.cookies:
            if cookie.startswith("ckan") and cookie not in ["ckan"]:
                response.delete_cookie(cookie)
            # Remove the ckan session cookie if not used e.g. logged out
            elif cookie == "ckan" and not c.user and not h.are_there_flash_messages():
                if session.id:
                    if not session.get("lang"):
                        session.delete()
                else:
                    response.delete_cookie(cookie)
            # Remove auth_tkt repoze.who cookie if user not logged in.
            elif cookie == "auth_tkt" and not session.id:
                response.delete_cookie(cookie)

        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()
开发者ID:gitter-badger,项目名称:ckan,代码行数:28,代码来源:base.py

示例10: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        try:
            res = WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()

        for cookie in request.cookies:
            # Remove the ckan session cookie if not used e.g. logged out
            if cookie == "ckan" and not c.user:
                # Check session for valid data (including flash messages)
                # (DGU also uses session for a shopping basket-type behaviour)
                is_valid_cookie_data = False
                for key, value in session.items():
                    if not key.startswith("_") and value:
                        is_valid_cookie_data = True
                        break
                if not is_valid_cookie_data:
                    if session.id:
                        self.log.debug("No valid session data - " "deleting session")
                        self.log.debug("Session: %r", session.items())
                        session.delete()
                    else:
                        self.log.debug("No session id - " "deleting session cookie")
                        response.delete_cookie(cookie)
            # Remove auth_tkt repoze.who cookie if user not logged in.
            elif cookie == "auth_tkt" and not session.id:
                response.delete_cookie(cookie)

        return res
开发者ID:Fiware,项目名称:context.Ckan,代码行数:34,代码来源:base.py

示例11: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""

        # Before we do anything, is there a "REMOTE USER"?
        # If not, we've not been authenticated!
        if not environ.get('REMOTE_USER') and 'login' not in environ.get('PATH_INFO'):
            raise httpexceptions.HTTPUnauthorized()

        # Redirect to a canonical form of the URL if necessary.
        self._redirect_noncanonical_url(environ)

        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict'

        if 'login' not in environ.get('PATH_INFO'):
            self.current_user = self._user_service.get_user_by_username(environ.get('REMOTE_USER'))

            if not self.current_user:
                raise httpexceptions.HTTPUnauthorized()

            if self.current_user.access_level == "Admin":
                c.admin_user = True
            else:
                c.admin_user = False

        return WSGIController.__call__(self, environ, start_response)
开发者ID:NERC-CEH,项目名称:ecomaps,代码行数:27,代码来源:base.py

示例12: __call__

 def __call__(self, environ, start_response):
     """Invoke the Controller"""
     # WSGIController.__call__ dispatches to the Controller method
     # the request is routed to. This routing information is
     # available in environ['pylons.routes_dict']
     start = time.time()
     try:
         self.ip_addr = _get_ip_addr(environ)
         # make sure that we update permissions each time we call controller
         api_key = request.GET.get("api_key")
         cookie_store = CookieStoreWrapper(session.get("rhodecode_user"))
         user_id = cookie_store.get("user_id", None)
         username = get_container_username(environ, config)
         auth_user = AuthUser(user_id, api_key, username)
         request.user = auth_user
         self.rhodecode_user = c.rhodecode_user = auth_user
         if not self.rhodecode_user.is_authenticated and self.rhodecode_user.user_id is not None:
             self.rhodecode_user.set_authenticated(cookie_store.get("is_authenticated"))
         log.info("IP: %s User: %s accessed %s" % (self.ip_addr, auth_user, safe_unicode(_get_access_path(environ))))
         return WSGIController.__call__(self, environ, start_response)
     finally:
         log.info(
             "IP: %s Request to %s time: %.3fs"
             % (_get_ip_addr(environ), safe_unicode(_get_access_path(environ)), time.time() - start)
         )
         meta.Session.remove()
开发者ID:yujiro,项目名称:rhodecode,代码行数:26,代码来源:base.py

示例13: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            self.ip_addr = _get_ip_addr(environ)
            # make sure that we update permissions each time we call controller
            api_key = request.GET.get('api_key')
            cookie_store = CookieStoreWrapper(session.get('rhodecode_user'))
            user_id = cookie_store.get('user_id', None)
            username = get_container_username(environ, config)
            try:
                auth_user = AuthUser(user_id, api_key, username, self.ip_addr)
            except UserCreationError, e:
                from rhodecode.lib import helpers as h
                h.flash(e, 'error')
                # container auth or other auth functions that create users on
                # the fly can throw this exception signaling that there's issue
                # with user creation, explanation should be provided in
                # Exception itself
                auth_user = AuthUser(ip_addr=self.ip_addr)

            request.user = auth_user
            self.rhodecode_user = c.rhodecode_user = auth_user
            if not self.rhodecode_user.is_authenticated and \
                       self.rhodecode_user.user_id is not None:
                self.rhodecode_user.set_authenticated(
                    cookie_store.get('is_authenticated')
                )
            log.info('IP: %s User: %s accessed %s' % (
               self.ip_addr, auth_user, safe_unicode(_get_access_path(environ)))
            )
            return WSGIController.__call__(self, environ, start_response)
开发者ID:adamscieszko,项目名称:rhodecode,代码行数:34,代码来源:base.py

示例14: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        return WSGIController.__call__(self, environ, start_response)
开发者ID:seanjensengrey,项目名称:cogen,代码行数:7,代码来源:base.py

示例15: __call__

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']

        # Insert any code to be run per request here.
        # hg parents --template="r{rev} {date|date} by {author}\n"
        hg_args = ['hg', 'parents', '--template="r{rev} {date|date} by {author}\n"']
        hg_process = subprocess.Popen(hg_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(__file__))
        c.revision = hg_process.stdout.readline().strip()[1:]
        if request.environ['HTTP_HOST'].startswith("comoto") and h.get_user(request.environ).superuser: #we are running on the production server and we are a superuser
            hg_args = ['hg', 'incoming', '--template="{rev}\n"']
            hg_process = subprocess.Popen(hg_args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=os.path.dirname(__file__))
            incoming_changesets = -2 #start with -4 because of extra lines printed
            while True:
                output = hg_process.stdout.readline()
		if len(output) > 2:
               	    incoming_changesets+=1
                if output.startswith("no"):
                    incoming_changesets = 0
                    break
                if output == '' or hg_process.poll() != None:
                    break
            c.incoming_changesets = incoming_changesets
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()
开发者ID:cemeyer2,项目名称:comoto,代码行数:29,代码来源:base.py


注:本文中的pylons.controllers.WSGIController类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。