本文整理汇总了Python中bottle.HTTPResponse方法的典型用法代码示例。如果您正苦于以下问题:Python bottle.HTTPResponse方法的具体用法?Python bottle.HTTPResponse怎么用?Python bottle.HTTPResponse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle
的用法示例。
在下文中一共展示了bottle.HTTPResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: proxy_trough_helper
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def proxy_trough_helper(url):
print ('PROXY-GET: {0}'.format(url))
proxy_response = requests.get(url)
if proxy_response.status_code == 200:
if proxy_response.headers['Last-Modified']:
response.set_header('Last-Modified', proxy_response.headers['Last-Modified'])
if proxy_response.headers['Content-Type']:
response.set_header('Content-Type', proxy_response.headers['Content-Type'])
if proxy_response.headers['Expires']:
response.set_header('Expires', proxy_response.headers['Expires'])
return proxy_response
else:
return HTTPResponse(status=proxy_response.status_code,
body=template(error_tpl,
headline='Error {0}'.format(proxy_response.status_code),
error='error during proxy call'))
#
# BOTTLE APP
#
示例2: image
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def image():
sample = int(request.query['sample'])
fileName,data = get_sample_from_num(sample)
ext = fileName.split('.')[-1]
if ext=="jpg":
header = "image/jpeg"
elif ext == "gif":
header = "image/gif"
elif ext == "png":
header = "image/png"
body = data
headers = dict()
headers['Content-Type'] = header
if 'c' in request.query:
headers['Cache-Control'] = "public, max-age=3600"
return HTTPResponse(body, **headers)
示例3: gt_image
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def gt_image():
imagesFilePath = os.path.dirname(os.path.abspath(__file__)) + "/gt/gt.zip"
archive = zipfile.ZipFile(imagesFilePath,'r')
fileName = request.query['sample']
ext = fileName.split('.')[-1]
if ext=="jpg":
header = "image/jpeg"
elif ext == "gif":
header = "image/gif"
elif ext == "png":
header = "image/png"
data = archive.read(fileName)
body = data
headers = dict()
headers['Content-Type'] = header
if 'c' in request.query:
headers['Cache-Control'] = "public, max-age=3600"
return HTTPResponse(body, **headers)
示例4: result_image
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def result_image():
submFilePath = os.path.dirname(os.path.abspath(__file__)) + "/output/results_" + str(request.query['m']) + ".zip"
archive = zipfile.ZipFile(submFilePath,'r')
fileName = request.query['name']
ext = fileName.split('.')[-1]
if ext=="jpg":
header = "image/jpeg"
elif ext == "gif":
header = "image/gif"
elif ext == "png":
header = "image/png"
data = archive.read(fileName)
body = data
headers = dict()
headers['Content-Type'] = header
if 'c' in request.query:
headers['Cache-Control'] = "public, max-age=3600"
return HTTPResponse(body, **headers)
示例5: static
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def static(path):
def copy(src, dst, n):
while n > 0:
d = src.read(min(n, 4096))
if d == "":
raise Exception()
dst.write(d)
n -= len(d)
length = int(bottle.request.headers.get("Content-Length", "0"))
if length <= 0 or bottle.request.headers.get("Content-Type", "") != "application/octet-stream":
bottle.abort(400)
path = "./" + path.strip("/")
if os.path.dirname(path) and not os.path.isdir(os.path.dirname(path)):
os.makedirs(os.path.dirname(path))
with tempfile.NamedTemporaryFile(dir=os.path.dirname(path)) as f:
copy(bottle.request["wsgi.input"], f, length)
os.rename(f.name, path)
f.delete = False
return bottle.HTTPResponse(status=201, headers={"Location": path[2:]})
示例6: testMaxAttemptsBlocked
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def testMaxAttemptsBlocked(self):
self.plugin = DOSBlockerBottlePlugin(self.memory,
delta=timedelta(seconds=0.1),
max_events=10,
bantime=timedelta(seconds=0.2),
banned_http_response=self.fake_response,
callback_ip_banned=self.bancallback
)
for i in xrange(10): # 0 to 9 failures
self.plugin.apply(self.callback, None)("hello")
self.assertEqual(i + 1, self.plugin.ip_count(self.ip))
self.callback.assert_called_with("hello")
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello2") # Blocked
try:
self.plugin.apply(self.callback, None)("hello2")
except HTTPResponse, e:
self.assertIn("Bonanza", e.body)
示例7: testBanExpired
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def testBanExpired(self):
self.plugin = DOSBlockerBottlePlugin(self.memory,
delta=timedelta(seconds=0.1),
max_events=10,
bantime=timedelta(seconds=0.4),
callback_ip_banned=self.bancallback)
for i in xrange(13): # 0 to 12 failures, banned
if i > 9:
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
else:
self.plugin.apply(self.callback, None)("hello")
#Wait delta time and make another fail, check keep banned
time.sleep(0.2)
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
#Wait to bantime and check again
time.sleep(0.21) # 0.2 + 0.2 >= Bantime
self.plugin.apply(self.callback, None)("hello2")
示例8: testCounterExpired
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def testCounterExpired(self):
self.plugin = MassiveErrorBlockerBottlePlugin(self.memory,
delta=timedelta(seconds=0.1),
max_events=10,
bantime=timedelta(seconds=0.2))
self.login_ok = False
for i in xrange(9): # 0 to 8 failures, 1 more left to ban
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
self.assertEqual(i + 1, self.plugin.ip_count(self.ip))
self.callback.assert_called_with("hello")
# Wait delta time and make another fail
time.sleep(0.11)
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
self.assertEqual(1, self.plugin.ip_count(self.ip))
self.login_ok = True
self.plugin.apply(self.callback, None)("hello2")
self.assertEquals(len(self.memory.memory), 0)
示例9: testBanExpired
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def testBanExpired(self):
self.plugin = MassiveErrorBlockerBottlePlugin(self.memory,
delta=timedelta(seconds=0.1),
max_events=10,
bantime=timedelta(seconds=0.2))
self.login_ok = False
for i in xrange(13): # 0 to 12 failures, banned
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
# Wait delta time and make another fail, check keep banned
time.sleep(0.1)
self.login_ok = True
self.assertRaises(HTTPResponse, self.plugin.apply(self.callback, None), "hello")
try:
self.plugin.apply(self.callback, None)("hello2")
except HTTPResponse, e:
self.assertIn("Banned", e.body)
# Wait to bantime and check again
示例10: __handle_action_queue
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def __handle_action_queue(self, file_name: str):
"""
Request a QUEUE action
:param file_name:
:return:
"""
# value is double encoded
file_name = unquote(file_name)
command = Controller.Command(Controller.Command.Action.QUEUE, file_name)
callback = WebResponseActionCallback()
command.add_callback(callback)
self.__controller.queue_command(command)
callback.wait()
if callback.success:
return HTTPResponse(body="Queued file '{}'".format(file_name))
else:
return HTTPResponse(body=callback.error, status=400)
示例11: __handle_action_extract
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def __handle_action_extract(self, file_name: str):
"""
Request a EXTRACT action
:param file_name:
:return:
"""
# value is double encoded
file_name = unquote(file_name)
command = Controller.Command(Controller.Command.Action.EXTRACT, file_name)
callback = WebResponseActionCallback()
command.add_callback(callback)
self.__controller.queue_command(command)
callback.wait()
if callback.success:
return HTTPResponse(body="Requested extraction for file '{}'".format(file_name))
else:
return HTTPResponse(body=callback.error, status=400)
示例12: __handle_action_delete_local
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def __handle_action_delete_local(self, file_name: str):
"""
Request a DELETE LOCAL action
:param file_name:
:return:
"""
# value is double encoded
file_name = unquote(file_name)
command = Controller.Command(Controller.Command.Action.DELETE_LOCAL, file_name)
callback = WebResponseActionCallback()
command.add_callback(callback)
self.__controller.queue_command(command)
callback.wait()
if callback.success:
return HTTPResponse(body="Requested local delete for file '{}'".format(file_name))
else:
return HTTPResponse(body=callback.error, status=400)
示例13: __handle_action_delete_remote
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def __handle_action_delete_remote(self, file_name: str):
"""
Request a DELETE REMOTE action
:param file_name:
:return:
"""
# value is double encoded
file_name = unquote(file_name)
command = Controller.Command(Controller.Command.Action.DELETE_REMOTE, file_name)
callback = WebResponseActionCallback()
command.add_callback(callback)
self.__controller.queue_command(command)
callback.wait()
if callback.success:
return HTTPResponse(body="Requested remote delete for file '{}'".format(file_name))
else:
return HTTPResponse(body=callback.error, status=400)
示例14: _static
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def _static(path):
response = None
if 'jinja_env' in _start_args and 'jinja_templates' in _start_args:
template_prefix = _start_args['jinja_templates'] + '/'
if path.startswith(template_prefix):
n = len(template_prefix)
template = _start_args['jinja_env'].get_template(path[n:])
response = btl.HTTPResponse(template.render())
if response is None:
response = btl.static_file(path, root=root_path)
_set_response_headers(response)
return response
示例15: _swagger_validate
# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPResponse [as 别名]
def _swagger_validate(self, callback, route, *args, **kwargs):
swagger_op = self._swagger_op(route)
if not swagger_op:
if self.ignore_undefined_routes or self._is_swagger_schema_route(route):
return callback(*args, **kwargs)
else:
return self.swagger_op_not_found_handler(route)
try:
if self.validate_requests:
try:
self._validate_request(swagger_op)
except ValidationError as e:
return self.invalid_request_handler(e)
result = callback(*args, **kwargs)
if self.validate_responses:
try:
self._validate_response(swagger_op, result)
except (ValidationError, MatchingResponseNotFound) as e:
return self.invalid_response_handler(e)
except Exception as e:
# Bottle handles redirects by raising an HTTPResponse instance
if isinstance(e, HTTPResponse):
raise e
return self.exception_handler(e)
return result