Python bottle.HTTPResponse() Examples

The following are 30 code examples of bottle.HTTPResponse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle , or try the search function .
Example #1
Source File: dos_blocker_test.py    From bii-server with MIT License 6 votes vote down vote up
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") 
Example #2
Source File: apiserver.py    From demobuilder with GNU General Public License v3.0 6 votes vote down vote up
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:]}) 
Example #3
Source File: massive_login_blocker_test.py    From bii-server with MIT License 6 votes vote down vote up
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 
Example #4
Source File: massive_login_blocker_test.py    From bii-server with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: proxy.py    From github-pages-basic-auth-proxy with MIT License 6 votes vote down vote up
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
# 
Example #6
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
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) 
Example #7
Source File: controller.py    From seedsync with Apache License 2.0 6 votes vote down vote up
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) 
Example #8
Source File: controller.py    From seedsync with Apache License 2.0 6 votes vote down vote up
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) 
Example #9
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
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) 
Example #10
Source File: web.py    From TedEval with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: controller.py    From seedsync with Apache License 2.0 6 votes vote down vote up
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) 
Example #12
Source File: controller.py    From seedsync with Apache License 2.0 6 votes vote down vote up
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) 
Example #13
Source File: dos_blocker_test.py    From bii-server with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: massive_login_blocker_test.py    From bii-server with MIT License 5 votes vote down vote up
def testMaxMinusOneAttemptsAllowed(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
            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")

        self.login_ok = True
        self.plugin.apply(self.callback, None)("hello2")
        self.callback.assert_called_with("hello2")  # If called, its not blocked 
Example #15
Source File: massive_login_blocker_test.py    From bii-server with MIT License 5 votes vote down vote up
def _callback(self, *args, **kwargs):
        if not self.login_ok:
            raise HTTPResponse("'Banned'",
                               "401 Unauthorized",
                               {"WWW-Authenticate": 'Basic realm="Login Required"'})
        return HTTPResponse("OK", "200 OK", {}) 
Example #16
Source File: non_ssl_blocker_test.py    From bii-server with MIT License 5 votes vote down vote up
def testHttpsERROR(self):
        self.plugin = NonSSLBlockerBottlePlugin()
        request.headers.get = Mock(return_value='http')
        self.assertRaises(HTTPResponse, self.plugin.apply(self._callback, None)) 
Example #17
Source File: api.py    From starter-snake-python with MIT License 5 votes vote down vote up
def end_response():
    return HTTPResponse(
        status=200
    ) 
Example #18
Source File: bson_bottle_test.py    From bii-server with MIT License 5 votes vote down vote up
def testAbortWithBSON(self):
        tmp = self.plugin.abort_with_bson(401, {"kk": 2})
        self.assertIsInstance(tmp, HTTPResponse)
        self.assertEquals("application/bson", tmp.content_type)
        self.assertEquals(401, tmp.status_code)
        self.assertEquals(str(BSON.encode({"kk": 2})), tmp.body) 
Example #19
Source File: integration_tests.py    From cccatalog-api with MIT License 5 votes vote down vote up
def _wait_for_callback(self, endpoint_name="/task_done"):
        """
        Block until a callback arrives. Time out if it doesn't arrive within
        10 seconds.
        :param endpoint_name:
        :return:
        """
        callback_listener = Bottle()
        # Signal when a callback has been received
        callback_received = multiprocessing.Value('i', 0)

        @callback_listener.route(endpoint_name, method="post")
        def handle_task_callback():
            callback_received.value = 1
            return HTTPResponse(status=204)

        kwargs = {
            'host': _get_host_ip(),
            'port': 58000,
            'quiet': (not ENABLE_DETAILED_LOGS)
        }
        cb_listener_process = Process(
            target=run,
            args=(callback_listener,),
            kwargs=kwargs
        )
        cb_listener_process.start()
        timeout_seconds = 10
        poll_time = 0.1
        running_time = 0
        while callback_received.value != 1:
            running_time += poll_time
            time.sleep(poll_time)
            if running_time >= timeout_seconds:
                cb_listener_process.terminate()
                self.fail('Timed out waiting for task callback.')
        cb_listener_process.terminate() 
Example #20
Source File: stub_maker.py    From lightbus with Apache License 2.0 5 votes vote down vote up
def method2(self) -> HTTPResponse:
        return HTTPResponse() 
Example #21
Source File: api.py    From starter-snake-python with MIT License 5 votes vote down vote up
def ping_response():
    return HTTPResponse(
        status=200
    ) 
Example #22
Source File: api.py    From starter-snake-python with MIT License 5 votes vote down vote up
def start_response(color):
    assert type(color) is str, \
        "Color value must be string"

    return HTTPResponse(
        status=200,
        headers={
            "Content-Type": "application/json"
        },
        body=json.dumps({
            "color": color
        })
    ) 
Example #23
Source File: api.py    From starter-snake-python with MIT License 5 votes vote down vote up
def move_response(move):
    assert move in ['up', 'down', 'left', 'right'], \
        "Move must be one of [up, down, left, right]"

    return HTTPResponse(
        status=200,
        headers={
            "Content-Type": "application/json"
        },
        body=json.dumps({
            "move": move
        })
    ) 
Example #24
Source File: http_basic_authentication_bottle_plugin.py    From bii-server with MIT License 5 votes vote down vote up
def get_invalid_header_response(self):
        """A response from a malformed header. Includes WWW-Authenticate for
        ask browser to request user and password"""
        return HTTPResponse("'Http Authentication not implemented'",
                    "401 Unauthorized",
                    {"WWW-Authenticate": 'Basic realm="Login Required"'}) 
Example #25
Source File: __init__.py    From NSC_BUILDER with MIT License 5 votes vote down vote up
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 
Example #26
Source File: server.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def __handle_action_restart(self):
        """
        Request a server restart
        :return:
        """
        self.logger.info("Received a restart action")
        self.__request_restart = True
        return HTTPResponse(body="Requested restart") 
Example #27
Source File: status.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def __handle_get_status(self):
        out_json = SerializeStatusJson.status(self.__status)
        return HTTPResponse(body=out_json) 
Example #28
Source File: config.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def __handle_get_config(self):
        out_json = SerializeConfig.config(self.__config)
        return HTTPResponse(body=out_json) 
Example #29
Source File: config.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def __handle_set_config(self, section: str, key: str, value: str):
        # value is double encoded
        value = unquote(value)

        if not self.__config.has_section(section):
            return HTTPResponse(body="There is no section '{}' in config".format(section), status=400)
        inner_config = getattr(self.__config, section)
        if not inner_config.has_property(key):
            return HTTPResponse(body="Section '{}' in config has no option '{}'".format(section, key), status=400)
        try:
            inner_config.set_property(key, value)
            return HTTPResponse(body="{}.{} set to {}".format(section, key, value))
        except ConfigError as e:
            return HTTPResponse(body=str(e), status=400) 
Example #30
Source File: auto_queue.py    From seedsync with Apache License 2.0 5 votes vote down vote up
def __handle_get_autoqueue(self):
        patterns = list(self.__auto_queue_persist.patterns)
        patterns.sort(key=lambda p: p.pattern)
        out_json = SerializeAutoQueue.patterns(patterns)
        return HTTPResponse(body=out_json)