Python http 模块,redirect() 实例源码

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

项目:lantern-detection    作者:gongxijun    | 项目源码 | 文件源码
def nomethod(cls):
    """Returns a `405 Method Not Allowed` error for `cls`."""
    web.ctx.status = '405 Method Not Allowed'
    web.header('Content-Type', 'text/html')
    web.header('Allow', \
           ', '.join([method for method in \
                     ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] \
                        if hasattr(cls, method)]))

    # commented out for the same reason redirect is
    # return output('method not allowed')
项目:lantern-detection    作者:gongxijun    | 项目源码 | 文件源码
def nomethod(cls):
    """Returns a `405 Method Not Allowed` error for `cls`."""
    web.ctx.status = '405 Method Not Allowed'
    web.header('Content-Type', 'text/html')
    web.header('Allow', \
           ', '.join([method for method in \
                     ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] \
                        if hasattr(cls, method)]))

    # commented out for the same reason redirect is
    # return output('method not allowed')
项目:birdnet    作者:cyysu    | 项目源码 | 文件源码
def nomethod(cls):
    """Returns a `405 Method Not Allowed` error for `cls`."""
    web.ctx.status = '405 Method Not Allowed'
    web.header('Content-Type', 'text/html')
    web.header('Allow', \
           ', '.join([method for method in \
                     ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] \
                        if hasattr(cls, method)]))

    # commented out for the same reason redirect is
    # return output('method not allowed')
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
        """Allows to use a special syntax for fast-check of
        `request.args()` validity.
        :params:
            i: index
            default: use this value if arg not found
            cast: type cast
            otherwise:
                will be executed when:
                    - casts fail
                    - value not found, dont have default and otherwise is
                    especified
                can be:
                    - None: results in a 404
                    - str: redirect to this address
                    - callable: calls the function (nothing is passed)
        Example:
            You can use::
                request.args(0,default=0,cast=int,otherwise='http://error_url')
                request.args(0,default=0,cast=int,otherwise=lambda:...)
        """
        n = len(self)
        if 0 <= i < n or -n <= i < 0:
            value = self[i]
        elif default is DEFAULT:
            value = None
        else:
            value, cast, otherwise = default, False, False
        try:
            if cast:
                value = cast(value)
            if not value and otherwise:
                raise ValueError('Otherwise will raised.')
        except (ValueError, TypeError):
            from http import HTTP, redirect
            if otherwise is None:
                raise HTTP(404)
            elif isinstance(otherwise, str):
                redirect(otherwise)
            elif callable(otherwise):
                return otherwise()
            else:
                raise RuntimeError("invalid otherwise")
        return value
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
        """Allows to use a special syntax for fast-check of
        `request.args()` validity.
        :params:
            i: index
            default: use this value if arg not found
            cast: type cast
            otherwise:
                will be executed when:
                    - casts fail
                    - value not found, dont have default and otherwise is
                    especified
                can be:
                    - None: results in a 404
                    - str: redirect to this address
                    - callable: calls the function (nothing is passed)
        Example:
            You can use::
                request.args(0,default=0,cast=int,otherwise='http://error_url')
                request.args(0,default=0,cast=int,otherwise=lambda:...)
        """
        n = len(self)
        if 0 <= i < n or -n <= i < 0:
            value = self[i]
        elif default is DEFAULT:
            value = None
        else:
            value, cast, otherwise = default, False, False
        try:
            if cast:
                value = cast(value)
            if not value and otherwise:
                raise ValueError('Otherwise will raised.')
        except (ValueError, TypeError):
            from http import HTTP, redirect
            if otherwise is None:
                raise HTTP(404)
            elif isinstance(otherwise, str):
                redirect(otherwise)
            elif callable(otherwise):
                return otherwise()
            else:
                raise RuntimeError("invalid otherwise")
        return value
项目:web3py    作者:web2py    | 项目源码 | 文件源码
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
        """Allows to use a special syntax for fast-check of
        `request.args()` validity.
        :params:
            i: index
            default: use this value if arg not found
            cast: type cast
            otherwise:
                will be executed when:
                    - casts fail
                    - value not found, dont have default and otherwise is
                    especified
                can be:
                    - None: results in a 404
                    - str: redirect to this address
                    - callable: calls the function (nothing is passed)
        Example:
            You can use::
                request.args(0,default=0,cast=int,otherwise='http://error_url')
                request.args(0,default=0,cast=int,otherwise=lambda:...)
        """
        n = len(self)
        if 0 <= i < n or -n <= i < 0:
            value = self[i]
        elif default is DEFAULT:
            value = None
        else:
            value, cast, otherwise = default, False, False
        try:
            if cast:
                value = cast(value)
            if not value and otherwise:
                raise ValueError('Otherwise will raised.')
        except (ValueError, TypeError):
            from http import HTTP, redirect
            if otherwise is None:
                raise HTTP(404)
            elif isinstance(otherwise, str):
                redirect(otherwise)
            elif callable(otherwise):
                return otherwise()
            else:
                raise RuntimeError("invalid otherwise")
        return value
项目:slugiot-client    作者:slugiot    | 项目源码 | 文件源码
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
        """Allows to use a special syntax for fast-check of
        `request.args()` validity.
        :params:
            i: index
            default: use this value if arg not found
            cast: type cast
            otherwise:
                will be executed when:
                    - casts fail
                    - value not found, dont have default and otherwise is
                    especified
                can be:
                    - None: results in a 404
                    - str: redirect to this address
                    - callable: calls the function (nothing is passed)
        Example:
            You can use::
                request.args(0,default=0,cast=int,otherwise='http://error_url')
                request.args(0,default=0,cast=int,otherwise=lambda:...)
        """
        n = len(self)
        if 0 <= i < n or -n <= i < 0:
            value = self[i]
        elif default is DEFAULT:
            value = None
        else:
            value, cast, otherwise = default, False, False
        try:
            if cast:
                value = cast(value)
            if not value and otherwise:
                raise ValueError('Otherwise will raised.')
        except (ValueError, TypeError):
            from http import HTTP, redirect
            if otherwise is None:
                raise HTTP(404)
            elif isinstance(otherwise, str):
                redirect(otherwise)
            elif callable(otherwise):
                return otherwise()
            else:
                raise RuntimeError("invalid otherwise")
        return value
项目:lantern-detection    作者:gongxijun    | 项目源码 | 文件源码
def handle(mapping, fvars=None):
    """
    Call the appropriate function based on the url to function mapping in `mapping`.
    If no module for the function is specified, look up the function in `fvars`. If
    `fvars` is empty, using the caller's context.

    `mapping` should be a tuple of paired regular expressions with function name
    substitutions. `handle` will import modules as necessary.
    """
    for url, ofno in utils.group(mapping, 2):
        if isinstance(ofno, tuple): 
            ofn, fna = ofno[0], list(ofno[1:])
        else: 
            ofn, fna = ofno, []
        fn, result = utils.re_subm('^' + url + '$', ofn, web.ctx.path)
        if result: # it's a match
            if fn.split(' ', 1)[0] == "redirect":
                url = fn.split(' ', 1)[1]
                if web.ctx.method == "GET":
                    x = web.ctx.env.get('QUERY_STRING', '')
                    if x: 
                        url += '?' + x
                return http.redirect(url)
            elif '.' in fn: 
                x = fn.split('.')
                mod, cls = '.'.join(x[:-1]), x[-1]
                mod = __import__(mod, globals(), locals(), [""])
                cls = getattr(mod, cls)
            else:
                cls = fn
                mod = fvars
                if isinstance(mod, types.ModuleType): 
                    mod = vars(mod)
                try: 
                    cls = mod[cls]
                except KeyError: 
                    return web.notfound()

            meth = web.ctx.method
            if meth == "HEAD":
                if not hasattr(cls, meth): 
                    meth = "GET"
            if not hasattr(cls, meth): 
                return nomethod(cls)
            tocall = getattr(cls(), meth)
            args = list(result.groups())
            for d in re.findall(r'\\(\d+)', ofn):
                args.pop(int(d) - 1)
            return tocall(*([x and urllib.unquote(x) for x in args] + fna))

    return web.notfound()
项目:lantern-detection    作者:gongxijun    | 项目源码 | 文件源码
def handle(mapping, fvars=None):
    """
    Call the appropriate function based on the url to function mapping in `mapping`.
    If no module for the function is specified, look up the function in `fvars`. If
    `fvars` is empty, using the caller's context.

    `mapping` should be a tuple of paired regular expressions with function name
    substitutions. `handle` will import modules as necessary.
    """
    for url, ofno in utils.group(mapping, 2):
        if isinstance(ofno, tuple): 
            ofn, fna = ofno[0], list(ofno[1:])
        else: 
            ofn, fna = ofno, []
        fn, result = utils.re_subm('^' + url + '$', ofn, web.ctx.path)
        if result: # it's a match
            if fn.split(' ', 1)[0] == "redirect":
                url = fn.split(' ', 1)[1]
                if web.ctx.method == "GET":
                    x = web.ctx.env.get('QUERY_STRING', '')
                    if x: 
                        url += '?' + x
                return http.redirect(url)
            elif '.' in fn: 
                x = fn.split('.')
                mod, cls = '.'.join(x[:-1]), x[-1]
                mod = __import__(mod, globals(), locals(), [""])
                cls = getattr(mod, cls)
            else:
                cls = fn
                mod = fvars
                if isinstance(mod, types.ModuleType): 
                    mod = vars(mod)
                try: 
                    cls = mod[cls]
                except KeyError: 
                    return web.notfound()

            meth = web.ctx.method
            if meth == "HEAD":
                if not hasattr(cls, meth): 
                    meth = "GET"
            if not hasattr(cls, meth): 
                return nomethod(cls)
            tocall = getattr(cls(), meth)
            args = list(result.groups())
            for d in re.findall(r'\\(\d+)', ofn):
                args.pop(int(d) - 1)
            return tocall(*([x and urllib.unquote(x) for x in args] + fna))

    return web.notfound()
项目:birdnet    作者:cyysu    | 项目源码 | 文件源码
def handle(mapping, fvars=None):
    """
    Call the appropriate function based on the url to function mapping in `mapping`.
    If no module for the function is specified, look up the function in `fvars`. If
    `fvars` is empty, using the caller's context.

    `mapping` should be a tuple of paired regular expressions with function name
    substitutions. `handle` will import modules as necessary.
    """
    for url, ofno in utils.group(mapping, 2):
        if isinstance(ofno, tuple): 
            ofn, fna = ofno[0], list(ofno[1:])
        else: 
            ofn, fna = ofno, []
        fn, result = utils.re_subm('^' + url + '$', ofn, web.ctx.path)
        if result: # it's a match
            if fn.split(' ', 1)[0] == "redirect":
                url = fn.split(' ', 1)[1]
                if web.ctx.method == "GET":
                    x = web.ctx.env.get('QUERY_STRING', '')
                    if x: 
                        url += '?' + x
                return http.redirect(url)
            elif '.' in fn: 
                x = fn.split('.')
                mod, cls = '.'.join(x[:-1]), x[-1]
                mod = __import__(mod, globals(), locals(), [""])
                cls = getattr(mod, cls)
            else:
                cls = fn
                mod = fvars
                if isinstance(mod, types.ModuleType): 
                    mod = vars(mod)
                try: 
                    cls = mod[cls]
                except KeyError: 
                    return web.notfound()

            meth = web.ctx.method
            if meth == "HEAD":
                if not hasattr(cls, meth): 
                    meth = "GET"
            if not hasattr(cls, meth): 
                return nomethod(cls)
            tocall = getattr(cls(), meth)
            args = list(result.groups())
            for d in re.findall(r'\\(\d+)', ofn):
                args.pop(int(d) - 1)
            return tocall(*([x and urllib.unquote(x) for x in args] + fna))

    return web.notfound()
项目:StuffShare    作者:StuffShare    | 项目源码 | 文件源码
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
        """Allows to use a special syntax for fast-check of `request.args()`
        validity

        Args:
            i: index
            default: use this value if arg not found
            cast: type cast
            otherwise: can be:

             - None: results in a 404
             - str: redirect to this address
             - callable: calls the function (nothing is passed)

        Example:
            You can use::

                request.args(0,default=0,cast=int,otherwise='http://error_url')
                request.args(0,default=0,cast=int,otherwise=lambda:...)

        """
        n = len(self)
        if 0 <= i < n or -n <= i < 0:
            value = self[i]
        elif default is DEFAULT:
            value = None
        else:
            value, cast = default, False
        if cast:
            try:
                value = cast(value)
            except (ValueError, TypeError):
                from http import HTTP, redirect
                if otherwise is None:
                    raise HTTP(404)
                elif isinstance(otherwise, str):
                    redirect(otherwise)
                elif callable(otherwise):
                    return otherwise()
                else:
                    raise RuntimeError("invalid otherwise")
        return value