Python cherrypy 模块,HTTPRedirect() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cherrypy.HTTPRedirect()

项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def scandeletemulti(self, ids, confirm=None):
        dbh = SpiderFootDb(self.config)
        names = list()

        for id in ids.split(','):
            res = dbh.scanInstanceGet(id)
            names.append(res[0])
            if res is None:
                return self.error("Scan ID not found (" + id + ").")

            if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
                return self.error("You cannot delete running scans.")

        if confirm is not None:
            for id in ids.split(','):
                dbh.scanInstanceDelete(id)
            raise cherrypy.HTTPRedirect("/")
        else:
            templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
            return templ.render(id=None, name=None, ids=ids.split(','), names=names, 
                                pageid="SCANLIST", docroot=self.docroot)
项目:otest    作者:rohe    | 项目源码 | 文件源码
def display_log(self, root, issuer="", profile="", testid=""):
        """

        :param root:
        :param issuer:
        :param profile:
        :param testid:
        :return:
        """
        logger.info(
            "display_log root: '{root}' issuer: '{iss}', profile: '{prof}' "
            "testid: '{tid}'".format(
                root=root, iss=issuer, prof=profile, tid=testid))

        if testid:
            path = os.path.join(root, issuer, profile, testid).replace(":",
                                                                       "%3A")
            raise cherrypy.HTTPRedirect(path)
        else:
            if issuer:
                return self._display(root, issuer, profile)
            else:
                return b'No saved logs'
项目:AlexaOPi    作者:dony71    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:AlexaPi    作者:alexa-pi    | 项目源码 | 文件源码
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": config['alexa']['Device_Type_ID'],
                "productInstanceAttributes": {
                    "deviceSerialNumber": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest()
                }
            }
        })

        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "code"
        payload = {
            "client_id": config['alexa']['Client_ID'],
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        prepared_req = req.prepare()
        raise cherrypy.HTTPRedirect(prepared_req.url)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def scandeletemulti(self, ids, confirm=None):
        dbh = SpiderFootDb(self.config)
        names = list()

        for id in ids.split(','):
            res = dbh.scanInstanceGet(id)
            names.append(res[0])
            if res is None:
                return self.error("Scan ID not found (" + id + ").")

            if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
                return self.error("You cannot delete running scans.")

        if confirm is not None:
            for id in ids.split(','):
                dbh.scanInstanceDelete(id)
            raise cherrypy.HTTPRedirect("/")
        else:
            templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
            return templ.render(id=None, name=None, ids=ids.split(','), names=names, 
                                pageid="SCANLIST", docroot=self.docroot)
项目:intel-edison-alexa    作者:pedrominatel    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:AlexaPiDEPRECATED    作者:alexa-pi    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:AlexaPi    作者:HighTeckMan    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:AlexaBeagleBone2    作者:merdahl    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"

        # Establish AMZN callback URL
        callback = cherrypy.url()  + "code"

        payload = { "client_id" : Client_ID,
                    "scope" : "alexa:all",
                    "scope_data" : sd,
                    "response_type" : "code", 
                    "redirect_uri" : callback }

        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:AlexaPi    作者:kgpayne    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:fedoidc    作者:OpenIDC    | 项目源码 | 文件源码
def index(self, uid='', iss=''):
        link = ''
        if iss:
            link = iss
        elif uid:
            try:
                link = self.rph.find_srv_discovery_url(
                    resource="acct:{}".format(uid))
            except requests.ConnectionError:
                raise cherrypy.HTTPError(
                    message="Webfinger lookup failed, connection error")
        else:
            fname = os.path.join(self.html_home, 'opbyuid.html')
            return as_bytes(open(fname, 'r').read())

        if link:
            resp_headers = self.rph.begin(link)
            raise cherrypy.HTTPRedirect(resp_headers['Location'])
项目:matrix-creator-alexa-voice-demo    作者:matrix-io    | 项目源码 | 文件源码
def index(self):
        scope = "alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "code"
        payload = {"client_id": Client_ID, "scope": "alexa:all",
                   "scope_data": sd, "response_type": "code", "redirect_uri": callback}
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:edison_developing    作者:vincentchung    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def do_login(self, username, password, from_page='..', **kwargs):
        """Login. May raise redirect, or return True if request handled."""
        response = cherrypy.serving.response
        error_msg = self.check_username_and_password(username, password)
        if error_msg:
            body = self.login_screen(from_page, username, error_msg)
            response.body = body
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        else:
            cherrypy.serving.request.login = username
            cherrypy.session[self.session_key] = username
            self.on_login(username)
            raise cherrypy.HTTPRedirect(from_page or '/')
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def trailing_slash(missing=True, extra=False, status=None, debug=False):
    """Redirect if path_info has (missing|extra) trailing slash."""
    request = cherrypy.serving.request
    pi = request.path_info

    if debug:
        cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' %
                     (request.is_index, missing, extra, pi),
                     'TOOLS.TRAILING_SLASH')
    if request.is_index is True:
        if missing:
            if not pi.endswith('/'):
                new_url = cherrypy.url(pi + '/', request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)
    elif request.is_index is False:
        if extra:
            # If pi == '/', don't redirect to ''!
            if pi.endswith('/') and pi != '/':
                new_url = cherrypy.url(pi[:-1], request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def run(self, point):
        """Execute all registered Hooks (callbacks) for the given point."""
        exc = None
        hooks = self[point]
        hooks.sort()
        for hook in hooks:
            # Some hooks are guaranteed to run even if others at
            # the same hookpoint fail. We will still log the failure,
            # but proceed on to the next hook. The only way
            # to stop all processing from one of these hooks is
            # to raise SystemExit and stop the whole server.
            if exc is None or hook.failsafe:
                try:
                    hook()
                except (KeyboardInterrupt, SystemExit):
                    raise
                except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
                        cherrypy.InternalRedirect):
                    exc = sys.exc_info()[1]
                except:
                    exc = sys.exc_info()[1]
                    cherrypy.log(traceback=True, severity=40)
        if exc:
            raise exc
项目:CodeLabs    作者:TheIoTLearningInitiative    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:Alexa    作者:respeaker    | 项目源码 | 文件源码
def index(self):
        scope = "alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "authresponse"
        payload = {"client_id": Client_ID, "scope": "alexa:all", "scope_data": sd, "response_type": "code",
                   "redirect_uri": callback}
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:pgwatch2    作者:cybertec-postgresql    | 项目源码 | 文件源码
def login(self, **params):
        print(params)
        message = ''
        submit = params.get('submit', False)
        user = params.get('user', '')
        password = params.get('password', '')
        returl = params.get('returl')

        if not cmd_args.no_anonymous_access:
            raise cherrypy.HTTPRedirect('/index')

        if submit:
            if user and password:
                if user == cmd_args.admin_user and password == cmd_args.admin_password:
                    # default, in-memory sessions
                    cherrypy.session['logged_in'] = True
                    cherrypy.session['login_time'] = time.time()
                    raise cherrypy.HTTPRedirect(returl if returl else '/index')
                else:
                    message = 'Wrong username and/or password!'
            else:
                message = 'Username and password needed!'
        tmpl = env.get_template('login.html')
        return tmpl.render(message=message, user=user, returl=returl)
项目:AlexaChipDEPRECATED    作者:alexa-pi    | 项目源码 | 文件源码
def index(self):
        scope="alexa_all"
        sd = json.dumps({
            "alexa:all": {
                "productID": ProductID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": "001"
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url()  + "code" 
        payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:alexa-client    作者:ewenchou    | 项目源码 | 文件源码
def index(self):
        sd = json.dumps({
            "alexa:all": {
                "productID": PRODUCT_ID,
                "productInstanceAttributes": {
                    "deviceSerialNumber": uuid.getnode()
                }
            }
        })
        url = "https://www.amazon.com/ap/oa"
        callback = cherrypy.url() + "authresponse"
        payload = {
            "client_id": CLIENT_ID,
            "scope": "alexa:all",
            "scope_data": sd,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request('GET', url, params=payload)
        p = req.prepare()
        raise cherrypy.HTTPRedirect(p.url)
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def do_login(self, username, password, from_page='..', **kwargs):
        """Login. May raise redirect, or return True if request handled."""
        response = cherrypy.serving.response
        error_msg = self.check_username_and_password(username, password)
        if error_msg:
            body = self.login_screen(from_page, username, error_msg)
            response.body = body
            if "Content-Length" in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers["Content-Length"]
            return True
        else:
            cherrypy.serving.request.login = username
            cherrypy.session[self.session_key] = username
            self.on_login(username)
            raise cherrypy.HTTPRedirect(from_page or "/")
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def trailing_slash(missing=True, extra=False, status=None, debug=False):
    """Redirect if path_info has (missing|extra) trailing slash."""
    request = cherrypy.serving.request
    pi = request.path_info

    if debug:
        cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' %
                     (request.is_index, missing, extra, pi),
                     'TOOLS.TRAILING_SLASH')
    if request.is_index is True:
        if missing:
            if not pi.endswith('/'):
                new_url = cherrypy.url(pi + '/', request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)
    elif request.is_index is False:
        if extra:
            # If pi == '/', don't redirect to ''!
            if pi.endswith('/') and pi != '/':
                new_url = cherrypy.url(pi[:-1], request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def run(self, point):
        """Execute all registered Hooks (callbacks) for the given point."""
        exc = None
        hooks = self[point]
        hooks.sort()
        for hook in hooks:
            # Some hooks are guaranteed to run even if others at
            # the same hookpoint fail. We will still log the failure,
            # but proceed on to the next hook. The only way
            # to stop all processing from one of these hooks is
            # to raise SystemExit and stop the whole server.
            if exc is None or hook.failsafe:
                try:
                    hook()
                except (KeyboardInterrupt, SystemExit):
                    raise
                except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
                        cherrypy.InternalRedirect):
                    exc = sys.exc_info()[1]
                except:
                    exc = sys.exc_info()[1]
                    cherrypy.log(traceback=True, severity=40)
        if exc:
            raise exc
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def setup_server():
        class Root:

            @cherrypy.expose
            def resource(self):
                return "Oh wah ta goo Siam."

            @cherrypy.expose
            def fail(self, code):
                code = int(code)
                if 300 <= code <= 399:
                    raise cherrypy.HTTPRedirect([], code)
                else:
                    raise cherrypy.HTTPError(code)

            @cherrypy.expose
            # In Python 3, tools.encode is on by default
            @cherrypy.config(**{'tools.encode.on': True})
            def unicoded(self):
                return ntou('I am a \u1ee4nicode string.', 'escape')

        conf = {'/': {'tools.etags.on': True,
                      'tools.etags.autotags': True,
                      }}
        cherrypy.tree.mount(Root(), config=conf)
项目:spiderfoot    作者:ParrotSec    | 项目源码 | 文件源码
def scandeletemulti(self, ids, confirm=None):
        dbh = SpiderFootDb(self.config)
        names = list()

        for id in ids.split(','):
            res = dbh.scanInstanceGet(id)
            names.append(res[0])
            if res is None:
                return self.error("Scan ID not found (" + id + ").")

            if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
                return self.error("You cannot delete running scans.")

        if confirm is not None:
            for id in ids.split(','):
                dbh.scanInstanceDelete(id)
            raise cherrypy.HTTPRedirect("/")
        else:
            templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
            return templ.render(id=None, name=None, ids=ids.split(','), names=names, 
                                pageid="SCANLIST", docroot=self.docroot)
项目:solaris-ips    作者:oracle    | 项目源码 | 文件源码
def manifest(self, *tokens):
                """Manifest requests coming from the BUI need to be redirected
                back through the RewriteRules defined in the Apache
                configuration in order to be served directly.
                pkg(1) will never hit this code, as those requests don't get
                handled by this webapp.
                """

                self.setup(cherrypy.request)
                rel_uri = cherrypy.request.path_info

                # we need to recover the escaped portions of the URI
                redir = rel_uri.lstrip("/").split("/")
                pub_mf = "/".join(redir[0:4])
                pkg_name = "/".join(redir[4:])
                # encode the URI so our RewriteRules can process them
                pkg_name = quote(pkg_name)
                pkg_name = pkg_name.replace("/", "%2F")
                pkg_name = pkg_name.replace("%40", "@", 1)

                # build a URI that we can redirect to
                redir = "{0}/{1}".format(pub_mf, pkg_name)
                redir = "/{0}".format(redir.lstrip("/"))
                raise cherrypy.HTTPRedirect(redir)
项目:otest    作者:rohe    | 项目源码 | 文件源码
def cont(self, **kwargs):
        path = kwargs['path']
        index = int(kwargs['index'])
        index += 1

        self.store_result()

        try:
            return self.run_flow(path, index=index)
        except cherrypy.HTTPRedirect:
            raise
        except Exception as err:
            exception_trace("", err, logger)
            self.store_result()
            return self.inut.err_response("run", err)
项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def scandelete(self, id, confirm=None):
        dbh = SpiderFootDb(self.config)
        res = dbh.scanInstanceGet(id)
        if res is None:
            return self.error("Scan ID not found.")

        if confirm is not None:
            dbh.scanInstanceDelete(id)
            raise cherrypy.HTTPRedirect("/")
        else:
            templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
            return templ.render(id=id, name=res[0], names=list(), ids=list(),
                                pageid="SCANLIST", docroot=self.docroot)
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def scandelete(self, id, confirm=None):
        dbh = SpiderFootDb(self.config)
        res = dbh.scanInstanceGet(id)
        if res is None:
            return self.error("Scan ID not found.")

        if confirm is not None:
            dbh.scanInstanceDelete(id)
            raise cherrypy.HTTPRedirect("/")
        else:
            templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
            return templ.render(id=id, name=res[0], names=list(), ids=list(),
                                pageid="SCANLIST", docroot=self.docroot)
项目:auth-tool    作者:luciddg    | 项目源码 | 文件源码
def index(self, username=None):
        if cherrypy.session.get('auth', False):
            raise cherrypy.HTTPRedirect('/update')
        else:
            return {'username': username}
项目:auth-tool    作者:luciddg    | 项目源码 | 文件源码
def update(self):
        if not cherrypy.session.get('auth', False):
            raise cherrypy.HTTPRedirect('/')
        else:
            return vars(cherrypy.session['user'])
项目:auth-tool    作者:luciddg    | 项目源码 | 文件源码
def logout(self):
        cherrypy.lib.sessions.expire()
        raise cherrypy.HTTPRedirect('/')
项目:RaspberryEcho    作者:ericpotvin    | 项目源码 | 文件源码
def index(self):
        """ The main page
        """

        product_id = Config.get_config(Config.FIELD_PRODUCT_ID)
        client_id = Config.get_config(Config.FIELD_CLIENT_ID)

        scope_data = json.dumps(
            {"alexa:all": {
            "productID": product_id,
            "productInstanceAttributes": {
                "deviceSerialNumber": "001"}
            }}
        )
        callback = cherrypy.url() + "code"

        payload = {
            "client_id": client_id,
            "scope": "alexa:all",
            "scope_data": scope_data,
            "response_type": "code",
            "redirect_uri": callback
        }
        req = requests.Request(
            'GET', AlexaService.AMAZON_BASE_URL, params=payload
        )
        raise cherrypy.HTTPRedirect(req.prepare().url)
项目:fedoidc    作者:OpenIDC    | 项目源码 | 文件源码
def conv_response(resp):
    if not isinstance(resp, Response):
        return as_bytes(resp)

    cookie = cherrypy.response.cookie
    for header, value in resp.headers:
        if header == 'Set-Cookie':
            cookie_obj = SimpleCookie(value)
            for name in cookie_obj:
                morsel = cookie_obj[name]
                cookie[name] = morsel.value
                for key in ['expires', 'path', 'comment', 'domain', 'max-age',
                            'secure', 'version']:
                    if morsel[key]:
                        cookie[name][key] = morsel[key]

    _stat = int(resp._status.split(' ')[0])
    #  if self.mako_lookup and self.mako_template:
    #    argv["message"] = message
    #    mte = self.mako_lookup.get_template(self.mako_template)
    #    return [mte.render(**argv)]
    if _stat < 300:
        cherrypy.response.status = _stat
        for key, val in resp.headers:
            cherrypy.response.headers[key] = val
        return as_bytes(resp.message)
    elif 300 <= _stat < 400:
        raise cherrypy.HTTPRedirect(resp.message, status=_stat)
    else:
        raise cherrypy.HTTPError(_stat, message=resp.message)
项目:SensorsHub    作者:SkewPL    | 项目源码 | 文件源码
def protect(self, bypass_in_demo_mode=False):
        """Returns user if he's logged in, otherwise redirects to login page"""

        # Check current logged in user
        user = self.current_user()

        # If allowed, return None when demo mode
        if user is not None or (bypass_in_demo_mode and self.core.config.get("demo_mode")):
            return user

        if user is None:
            raise cherrypy.HTTPRedirect("/settings/login")
项目:SensorsHub    作者:SkewPL    | 项目源码 | 文件源码
def login(self, **kwargs):
        """Login web page, available at /settings/login"""
        if "user" in kwargs and "pass" in kwargs:
            if self.core.accounts.login_user(kwargs["user"], kwargs["pass"]) is not None:
                raise cherrypy.HTTPRedirect("/settings")
            else:
                return self.render("/settings/login.html", error=self.core.lang.get("error_wrong_username_or_password"))

        return self.render("/settings/login.html")
项目:thermostat_ita    作者:jpnos26    | 项目源码 | 文件源码
def check_auth(*args, **kwargs):
    """A tool that looks in config for 'auth.require'. If found and it
    is not None, a login is required and the entry is evaluated as a list of
    conditions that the user must fulfill"""
    conditions = cherrypy.request.config.get('auth.require', None)
    if conditions is not None:
        username = cherrypy.session.get(SESSION_KEY)
        if username:
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true or false
                if not condition():
                    raise cherrypy.HTTPRedirect("/auth/login")
        else:
            raise cherrypy.HTTPRedirect("/auth/login")
项目:thermostat_ita    作者:jpnos26    | 项目源码 | 文件源码
def login(self, username=None, password=None, from_page="/"):
        if username is None or password is None:
            return self.get_loginform("", from_page=from_page)

        error_msg = check_credentials(username, password)
        if error_msg:
            return self.get_loginform(username, error_msg, from_page)
        else:
            cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
            self.on_login(username)
            raise cherrypy.HTTPRedirect(from_page or "/")
项目:thermostat_ita    作者:jpnos26    | 项目源码 | 文件源码
def logout(self, from_page="/"):
        sess = cherrypy.session
        username = sess.get(SESSION_KEY, None)
        sess[SESSION_KEY] = None
        if username:
            cherrypy.request.login = None
            self.on_logout(username)
        raise cherrypy.HTTPRedirect(from_page or "/")

#from auth import AuthController, require, member_of, name_is
项目:thermostat_ita    作者:jpnos26    | 项目源码 | 文件源码
def check_auth(*args, **kwargs):
    """A tool that looks in config for 'auth.require'. If found and it
    is not None, a login is required and the entry is evaluated as a list of
    conditions that the user must fulfill"""
    conditions = cherrypy.request.config.get('auth.require', None)
    if conditions is not None:
        username = cherrypy.session.get(SESSION_KEY)
        if username:
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true or false
                if not condition():
                    raise cherrypy.HTTPRedirect("/auth/login")
        else:
            raise cherrypy.HTTPRedirect("/auth/login")
项目:thermostat_ita    作者:jpnos26    | 项目源码 | 文件源码
def login(self, username=None, password=None, from_page="/"):
        if username is None or password is None:
            return self.get_loginform("", from_page=from_page)

        error_msg = check_credentials(username, password)
        if error_msg:
            return self.get_loginform(username, error_msg, from_page)
        else:
            cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
            self.on_login(username)
            raise cherrypy.HTTPRedirect(from_page or "/")
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def pause(self, namespace):
        logging.statistics.get(namespace, {})['Enabled'] = False
        raise cherrypy.HTTPRedirect('./')
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def resume(self, namespace):
        logging.statistics.get(namespace, {})['Enabled'] = True
        raise cherrypy.HTTPRedirect('./')
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def validate_since():
    """Validate the current Last-Modified against If-Modified-Since headers.

    If no code has set the Last-Modified response header, then no validation
    will be performed.
    """
    response = cherrypy.serving.response
    lastmod = response.headers.get('Last-Modified')
    if lastmod:
        status, reason, msg = _httputil.valid_status(response.status)

        request = cherrypy.serving.request

        since = request.headers.get('If-Unmodified-Since')
        if since and since != lastmod:
            if (status >= 200 and status <= 299) or status == 412:
                raise cherrypy.HTTPError(412)

        since = request.headers.get('If-Modified-Since')
        if since and since == lastmod:
            if (status >= 200 and status <= 299) or status == 304:
                if request.method in ('GET', 'HEAD'):
                    raise cherrypy.HTTPRedirect([], 304)
                else:
                    raise cherrypy.HTTPError(412)


#                                Tool code                                #
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def do_logout(self, from_page='..', **kwargs):
        """Logout. May raise redirect, or return True if request handled."""
        sess = cherrypy.session
        username = sess.get(self.session_key)
        sess[self.session_key] = None
        if username:
            cherrypy.serving.request.login = None
            self.on_logout(username)
        raise cherrypy.HTTPRedirect(from_page)
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def redirect(self, url):
        raise cherrypy.HTTPRedirect(url)
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def handle_error(self):
        """Handle the last unanticipated exception. (Core)"""
        try:
            self.hooks.run('before_error_response')
            if self.error_response:
                self.error_response()
            self.hooks.run('after_error_response')
            cherrypy.serving.response.finalize()
        except cherrypy.HTTPRedirect:
            inst = sys.exc_info()[1]
            inst.set_response()
            cherrypy.serving.response.finalize()

    # ------------------------- Properties ------------------------- #
项目:xd    作者:century-arcade    | 项目源码 | 文件源码
def index(self):
        raise cherrypy.HTTPRedirect("/search")
项目:pgwatch2    作者:cybertec-postgresql    | 项目源码 | 文件源码
def logged_in(f: callable, *args, **kwargs):
    if cmd_args.no_anonymous_access:
        if not cherrypy.session.get('logged_in'):
            url = cherrypy.url()    # http://0.0.0.0:8080/dbs
            splits = url.split('/') # ['https:', '', '0.0.0.0:8080', 'dbs']
            if len(splits) > 3 and splits[3] in ['dbs', 'metrics', 'logs']:
                raise cherrypy.HTTPRedirect('/login' + ('?returl=/' + '/'.join(splits[3:])))
            else:
                raise cherrypy.HTTPRedirect('/login')
    return f(*args, **kwargs)