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


Python request.path方法代码示例

本文整理汇总了Python中bottle.request.path方法的典型用法代码示例。如果您正苦于以下问题:Python request.path方法的具体用法?Python request.path怎么用?Python request.path使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bottle.request的用法示例。


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

示例1: WSGIHandler

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def WSGIHandler(environ, start_response):
    """The bottle WSGI-handler."""
    global request     # 引用全局变量
    global response

    request.bind(environ)
    response.bind()
    ###############################################################################

    try:
        handler, args = match_url(request.path, request.method)  # 调用,下面定义.
        if not handler:
            raise HTTPError(404, "Not found")
        output = handler(**args)
    except BreakTheBottle, shard:
        output = shard.output 
开发者ID:hhstore,项目名称:annotated-py-bottle,代码行数:18,代码来源:bottle.py

示例2: mount

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def mount(self, app, script_path):
        ''' Mount a Bottle application to a specific URL prefix '''
        if not isinstance(app, Bottle):
            raise TypeError('Only Bottle instances are supported for now.')
        script_path = '/'.join(filter(None, script_path.split('/')))
        path_depth = script_path.count('/') + 1
        if not script_path:
            raise TypeError('Empty script_path. Perhaps you want a merge()?')
        for other in self.mounts:
            if other.startswith(script_path):
                raise TypeError('Conflict with existing mount: %s' % other)
        @self.route('/%s/:#.*#' % script_path, method="ANY")
        def mountpoint():
            request.path_shift(path_depth)
            return app.handle(request.path, request.method)
        self.mounts[script_path] = app 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:18,代码来源:bottle2.py

示例3: route

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def route(self, path=None, method='GET', **kargs):
        """ Decorator: Bind a function to a GET request path.

            If the path parameter is None, the signature of the decorated
            function is used to generate the path. See yieldroutes()
            for details.

            The method parameter (default: GET) specifies the HTTP request
            method to listen to. You can specify a list of methods.
        """
        if isinstance(method, str): #TODO: Test this
            method = method.split(';')
        def wrapper(callback):
            paths = [] if path is None else [path.strip().lstrip('/')]
            if not paths: # Lets generate the path automatically
                paths = yieldroutes(callback)
            for p in paths:
                for m in method:
                    route = m.upper() + ';' + p
                    self.routes.add(route, callback, **kargs)
            return callback
        return wrapper 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:24,代码来源:bottle2.py

示例4: __call__

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def __call__(self, environ, start_response):
        """ The bottle WSGI-interface. """
        try:
            request.bind(environ, self)
            response.bind(self)
            out = self.handle(request.path, request.method)
            out = self._cast(out, request, response)
            if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
                out = [] # rfc2616 section 4.3
            status = '%d %s' % (response.status, HTTP_CODES[response.status])
            start_response(status, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception, e:
            if not self.catchall:
                raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % environ.get('PATH_INFO', '/')
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
                err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
            environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
            start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
            return [tob(err)] 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:27,代码来源:bottle2.py

示例5: path_shift

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def path_shift(self, count=1):
        ''' Shift some levels of PATH_INFO into SCRIPT_NAME and return the
            moved part. count defaults to 1'''
        #/a/b/  /c/d  --> 'a','b'  'c','d'
        if count == 0: return ''
        pathlist = self.path.strip('/').split('/')
        scriptlist = self.environ.get('SCRIPT_NAME','/').strip('/').split('/')
        if pathlist and pathlist[0] == '': pathlist = []
        if scriptlist and scriptlist[0] == '': scriptlist = []
        if count > 0 and count <= len(pathlist):
            moved = pathlist[:count]
            scriptlist = scriptlist + moved
            pathlist = pathlist[count:]
        elif count < 0 and count >= -len(scriptlist):
            moved = scriptlist[count:]
            pathlist = moved + pathlist
            scriptlist = scriptlist[:count]
        else:
            empty = 'SCRIPT_NAME' if count < 0 else 'PATH_INFO'
            raise AssertionError("Cannot shift. Nothing left from %s" % empty)
        self['PATH_INFO'] = self.path =  '/' + '/'.join(pathlist) \
                          + ('/' if self.path.endswith('/') and pathlist else '')
        self['SCRIPT_NAME'] = '/' + '/'.join(scriptlist)
        return '/'.join(moved) 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:26,代码来源:bottle2.py

示例6: __init__

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', settings={}):
        """ Create a new template.
        If the source parameter (str or buffer) is missing, the name argument
        is used to guess a template filename. Subclasses can assume that
        self.source and/or self.filename are set. Both are strings.
        The lookup, encoding and settings parameters are stored as instance
        variables.
        The lookup parameter stores a list containing directory paths.
        The encoding parameter should be used to decode byte strings or files.
        The settings parameter contains a dict for engine-specific settings.
        """
        self.name = name
        self.source = source.read() if hasattr(source, 'read') else source
        self.filename = source.filename if hasattr(source, 'filename') else None
        self.lookup = map(os.path.abspath, lookup)
        self.encoding = encoding
        self.settings = self.settings.copy() # Copy from class variable
        self.settings.update(settings) # Apply
        if not self.source and self.name:
            self.filename = self.search(self.name, self.lookup)
            if not self.filename:
                raise TemplateError('Template %s not found.' % repr(name))
        if not self.source and not self.filename:
            raise TemplateError('No template specified.')
        self.prepare(**self.settings) 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:27,代码来源:bottle2.py

示例7: route

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def route(self, path=None, method='GET', **kargs):
        """ Decorator: Bind a function to a GET request path.

            If the path parameter is None, the signature of the decorated
            function is used to generate the path. See yieldroutes()
            for details.

            The method parameter (default: GET) specifies the HTTP request
            method to listen to. You can specify a list of methods. 
        """
        if isinstance(method, str): #TODO: Test this
            method = method.split(';')
        def wrapper(callback):
            paths = [] if path is None else [path.strip().lstrip('/')]
            if not paths: # Lets generate the path automatically 
                paths = yieldroutes(callback)
            for p in paths:
                for m in method:
                    route = m.upper() + ';' + p
                    self.routes.add(route, callback, **kargs)
            return callback
        return wrapper 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:24,代码来源:bottle3.py

示例8: __call__

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def __call__(self, environ, start_response):
        """ The bottle WSGI-interface. """
        try:
            request.bind(environ, self)
            response.bind(self)
            out = self.handle(request.path, request.method)
            out = self._cast(out, request, response)
            if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
                out = [] # rfc2616 section 4.3
            status = '%d %s' % (response.status, HTTP_CODES[response.status])
            start_response(status, response.headerlist)
            return out
        except (KeyboardInterrupt, SystemExit, MemoryError):
            raise
        except Exception as e:
            if not self.catchall:
                raise
            err = '<h1>Critical error while processing request: %s</h1>' \
                  % environ.get('PATH_INFO', '/')
            if DEBUG:
                err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
                err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
            environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
            start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
            return [tob(err)] 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:27,代码来源:bottle3.py

示例9: bind

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def bind(self, environ, app=None):
        """ Bind a new WSGI enviroment and clear out all previously computed
            attributes.
            
            This is done automatically for the global `bottle.request`
            instance on every request.
        """
        if isinstance(environ, Request): # Recycle already parsed content
            for key in self.__dict__: #TODO: Test this
                setattr(self, key, getattr(environ, key))
            self.app = app
            return
        self._GET = self._POST = self._GETPOST = self._COOKIES = None
        self._body = self._header = None
        self.environ = environ
        self.app = app
        # These attributes are used anyway, so it is ok to compute them here
        self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/')
        self.method = environ.get('REQUEST_METHOD', 'GET').upper() 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:21,代码来源:bottle3.py

示例10: yieldroutes

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def yieldroutes(func):
    """ Return a generator for routes that match the signature (name, args) 
    of the func parameter. This may yield more than one route if the function
    takes optional keyword arguments. The output is best described by example:
      a()         -> '/a'
      b(x, y)     -> '/b/:x/:y'
      c(x, y=5)   -> '/c/:x' and '/c/:x/:y'
      d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y'
    """
    path = func.__name__.replace('__','/').lstrip('/')
    spec = inspect.getargspec(func)
    argc = len(spec[0]) - len(spec[3] or [])
    path += ('/:%s' * argc) % tuple(spec[0][:argc])
    yield path
    for arg in spec[0][argc:]:
        path += '/:%s' % arg
        yield path






# Decorators
#TODO: Replace default_app() with app() 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:27,代码来源:bottle3.py

示例11: schedule

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def schedule(req):
    """Schedule or unschedule a job
    TODO add a lock
    """
    name = req['Name']
    timer = req['Timer']
    action = req['Action']
    schedule = []
    if timer:  # 0 means unschedule!
        schedule.append((name, action, timer))
    if os.path.exists(SCHEDULE):
        with open(SCHEDULE) as f:
            for n, a, t in csv.reader(f):
                # skip the line we want to write
                if n == name and a == action:
                    continue
                schedule.append((n, a, t))
    os.makedirs(dirname(SCHEDULE), exist_ok=True)
    with open(SCHEDULE, 'w') as f:
        for line in schedule:
            csv.writer(f).writerow(line)
    return {'Err': ''} 
开发者ID:anybox,项目名称:buttervolume,代码行数:24,代码来源:plugin.py

示例12: dispatch

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def dispatch(url):
    """
        This class is the beginning of all entrypoints in the Ray API. Here, each url
        will be redirect to the right handler
    """

    url = bottle_req.path
    log.info('request: %s', bottle_req.url)

    if url[-1] == '/':
        url = url[:-1]

    response_code = 200

    try:
        processed = process(url, bottle_req, bottle_resp)

        try:
            from_func, http_status = processed[0], processed[1]
            bottle_resp.status = http_status
            return from_func
        except:
            return processed

    except exceptions.RayException as e:
        log.exception('ray exception: ')
        response_code = e.http_code

    except:
        log.exception('exception:')
        raise

    bottle_resp.status = response_code 
开发者ID:felipevolpone,项目名称:ray,代码行数:35,代码来源:api.py

示例13: bind

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def bind(self, environ):  # 请求,绑定
        """ Binds the enviroment of the current request to this request handler """
        self._environ = environ
        self._GET = None
        self._POST = None
        self._GETPOST = None
        self._COOKIES = None
        self.path = self._environ.get('PATH_INFO', '/').strip()
        if not self.path.startswith('/'):
            self.path = '/' + self.path 
开发者ID:hhstore,项目名称:annotated-py-bottle,代码行数:12,代码来源:bottle.py

示例14: set_cookie

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def set_cookie(self, key, value, **kargs):
        """ Sets a Cookie. Optional settings: expires, path, comment, domain, max-age, secure, version, httponly """
        self.COOKIES[key] = value
        for k in kargs:
            self.COOKIES[key][k] = kargs[k] 
开发者ID:hhstore,项目名称:annotated-py-bottle,代码行数:7,代码来源:bottle.py

示例15: send_file

# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import path [as 别名]
def send_file(filename, root, guessmime=True, mimetype='text/plain'):
    """ Aborts execution and sends a static files as response. """
    root = os.path.abspath(root) + '/'
    filename = os.path.normpath(filename).strip('/')
    filename = os.path.join(root, filename)

    if not filename.startswith(root):    # HTTP状态码: 401
        abort(401, "Access denied.")
    if not os.path.exists(filename) or not os.path.isfile(filename):
        abort(404, "File does not exist.")     # 文件不存在
    if not os.access(filename, os.R_OK):
        abort(401, "You do not have permission to access this file.")

    if guessmime:
        guess = mimetypes.guess_type(filename)[0]
        if guess:
            response.content_type = guess
        elif mimetype:
            response.content_type = mimetype
    elif mimetype:
        response.content_type = mimetype

    stats = os.stat(filename)
    # TODO: HTTP_IF_MODIFIED_SINCE -> 304 (Thu, 02 Jul 2009 23:16:31 CEST)
    if 'Content-Length' not in response.header:
        response.header['Content-Length'] = stats.st_size
    if 'Last-Modified' not in response.header:
        ts = time.gmtime(stats.st_mtime)
        ts = time.strftime("%a, %d %b %Y %H:%M:%S +0000", ts)
        response.header['Last-Modified'] = ts

    raise BreakTheBottle(open(filename, 'r'))    # 抛出异常


###############################################################################
###############################################################################
###############################################################################


# Routing   路由处理部分-定义 
开发者ID:hhstore,项目名称:annotated-py-bottle,代码行数:42,代码来源:bottle.py


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