本文整理汇总了Python中bottle.request.method方法的典型用法代码示例。如果您正苦于以下问题:Python request.method方法的具体用法?Python request.method怎么用?Python request.method使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.request
的用法示例。
在下文中一共展示了request.method方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: WSGIHandler
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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: compile_route
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def compile_route(route): # 编译路由串
""" Compiles a route string and returns a precompiled RegexObject.
Routes may contain regular expressions with named groups to support url parameters.
Example: '/user/(?P<id>[0-9]+)' will match '/user/5' with {'id':'5'}
A more human readable syntax is supported too.
Example: '/user/:id/:action' will match '/user/5/kiss' with {'id':'5', 'action':'kiss'}
"""
route = route.strip().lstrip('$^/ ').rstrip('$^ ') # 字符串过滤字符.
route = re.sub(r':([a-zA-Z_]+)(?P<uniq>[^\w/])(?P<re>.+?)(?P=uniq)', r'(?P<\1>\g<re>)', route)
route = re.sub(r':([a-zA-Z_]+)', r'(?P<\1>[^/]+)', route)
return re.compile('^/%s$' % route) # 路由需要正则表达式处理.
###############################################################################
# 功能: URL 匹配
#
# 参数:
# - url: 路由地址
# - method: 请求的方法, GET, POST 等
###############################################################################
示例3: add_route
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def add_route(route, handler, method='GET', simple=False):
""" Adds a new route to the route mappings.
Example:
def hello():
return "Hello world!"
add_route(r'/hello', hello)"""
method = method.strip().upper() # 对请求参数,作统一格式化
if re.match(r'^/(\w+/)*\w*$', route) or simple: # 正则匹配路由
ROUTES_SIMPLE.setdefault(method, {})[route] = handler # 更新全局路由字典
else:
route = compile_route(route) # 调用, 定义在前面.
ROUTES_REGEXP.setdefault(method, []).append([route, handler]) # 更新全局路由字典
###############################################################################
# 功能: 路由装饰器
#
# 参数:
# - url:
#
# 依赖:
# - 包裹函数: add_route()
#
示例4: mount
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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
示例5: route
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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
示例6: __call__
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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)]
示例7: mount
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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([_f for _f in script_path.split('/') if _f])
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
示例8: route
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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
示例9: handle
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def handle(self, url, method):
""" Execute the handler bound to the specified url and method and return
its output. If catchall is true, exceptions are catched and returned as
HTTPError(500) objects. """
if not self.serve:
return HTTPError(503, "Server stopped")
handler, args = self.match_url(url, method)
if not handler:
return HTTPError(404, "Not found:" + url)
try:
return handler(**args)
except HTTPResponse as e:
return e
except Exception as e:
if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\
or not self.catchall:
raise
return HTTPError(500, 'Unhandled exception', e, format_exc(10))
示例10: __call__
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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)]
示例11: bind
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [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()
示例12: set_cors_headers
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def set_cors_headers():
"""
Set CORS headers
"""
if request.method == 'GET':
response.set_header(b'Access-Control-Allow-Origin', b'*')
return
if request.method == 'OPTIONS':
response.set_header(b'Access-Control-Allow-Methods',
b'GET, PUT, HEAD, DELETE, OPTIONS')
response.set_header(b'Access-Control-Allow-Headers',
b'authorization')
client_origin = request.get_header(b'Origin', b'*')
# for PUT and DELETE operations, echo back the given Origin header.
response.set_header(b'Access-Control-Allow-Origin', client_origin)
示例13: _swagger_op
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def _swagger_op(self, route):
# Convert bottle "<param>" style path params to swagger "{param}" style
path = re.sub(r'/<(.+?)>', r'/{\1}', route.rule)
return self.swagger.get_op_for_request(request.method, path)
示例14: method
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def method(self): # 请求类型: GET,POST 等.
''' Returns the request method (GET,POST,PUT,DELETE,...) '''
return self._environ.get('REQUEST_METHOD', 'GET').upper()
示例15: match_url
# 需要导入模块: from bottle import request [as 别名]
# 或者: from bottle.request import method [as 别名]
def match_url(self, path, method='GET'):
""" Find a callback bound to a path and a specific HTTP method.
Return (callback, param) tuple or (None, {}).
method: HEAD falls back to GET. HEAD and GET fall back to ALL.
"""
path = path.strip().lstrip('/')
handler, param = self.routes.match(method + ';' + path)
if handler: return handler, param
if method == 'HEAD':
handler, param = self.routes.match('GET;' + path)
if handler: return handler, param
handler, param = self.routes.match('ANY;' + path)
if handler: return handler, param
return None, {}