本文整理匯總了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
示例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
示例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
示例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)]
示例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)
示例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)
示例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
示例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)]
示例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()
示例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()
示例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': ''}
示例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
示例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
示例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]
示例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 路由處理部分-定義