How to use the bottle.HTTPResponse function in bottle

To help you get started, we’ve selected a few bottle examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pakerfeldt / remotestick-server / bottle.py View on Github external
if download:
        header['Content-Disposition'] = 'attachment; filename="%s"' % download

    stats = os.stat(filename)
    lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime))
    header['Last-Modified'] = lm
    ims = request.environ.get('HTTP_IF_MODIFIED_SINCE')
    if ims:
        ims = ims.split(";")[0].strip() # IE sends "; length=146"
        ims = parse_date(ims)
        if ims is not None and ims >= int(stats.st_mtime):
            header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
            return HTTPResponse(status=304, header=header)
    header['Content-Length'] = stats.st_size
    if request.method == 'HEAD':
        return HTTPResponse('', header=header)
    else:
        return HTTPResponse(open(filename, 'rb'), header=header)
github beloglazov / openstack-neat / neat / globals / manager.py View on Github external
def raise_error(status_code):
    """ Raise and HTTPResponse exception with the specified status code.

    :param status_code: An HTTP status code of the error.
     :type status_code: int
    """
    if status_code in ERRORS:
        if status_code == 412 and log.isEnabledFor(logging.INFO):
            log.info('REST service: %s', ERRORS[status_code])
        else:
            log.error('REST service: %s', ERRORS[status_code])
        raise bottle.HTTPResponse(ERRORS[status_code], status_code)
    log.error('REST service: Unknown error')
    raise bottle.HTTPResponse('Unknown error', 500)
github tdorssers / ztp / app.py View on Github external
def error(msg):
    """ Sends HTTP 500 with error message string by raising HTTPResponse """
    raise bottle.HTTPResponse(body=json.dumps(str(msg)), status=500,
                              headers={'Content-type': 'application/json'})
github OpenChemistry / tomviz / acquisition / tomviz / acquisition / server.py View on Github external
def _log(log):
    bottle.response.headers['Content-Type'] = 'text/plain'
    bytes = request.query.bytes

    if log not in tomviz.LOG_PATHS:
        raise HTTPResponse(body='Invalid log parameter: %s.' % log,
                           status=400)
    path = tomviz.LOG_PATHS[log]

    if not os.path.exists(path):
        raise HTTPResponse(body='Log file does not exist.',
                           status=400)

    file_size = os.path.getsize(path)
    length = int(bytes) or file_size
    file_size1 = 0
    if length > file_size:
        path1 = path + '.1'
        if os.path.exists(path1):
            file_size1 = os.path.getsize(path1)

    def stream():
github oferb / OpenTrains / gae_collector / main.py View on Github external
def _wrap(*args,**kwargs):
		try:
			res = func(*args,**kwargs)
		except HTTPResponse,h:
			raise h
		except Exception,e:
			raise_error(unicode(e))
		return res
	return _wrap
github bottlepy / bottle / plugins / werkzeug / bottle_werkzeug.py View on Github external
def wrapper(*a, **ka):
            environ = bottle.request.environ
            bottle.local.werkzueg_request = self.request_class(environ)
            try:
                rv = callback(*a, **ka)
            except werkzeug.exceptions.HTTPException, e:
                rv = e.get_response(environ)
            if isinstance(rv, werkzeug.BaseResponse):
                rv = bottle.HTTPResponse(rv.iter_encoded(), rv.status_code, rv.header_list)
            return rv
        return wrapper
github pretenders / pretenders / pretenders / http / server.py View on Github external
def replay(self, url):
        """
        Replay a previously recorded preset, and save the request in history
        """
        request_info = RequestSerialiser(url, bottle.request)
        body = request_info.serialize()
        LOGGER.info("Replaying URL for request: \n{0}".format(body))
        boss_response = self.store_history_retrieve_preset(body)

        if boss_response.status == 200:
            preset = Preset(boss_response.read())
            return preset.as_http_response(bottle.response)
        else:
            LOGGER.error("Cannot find matching request\n{0}".format(body))
            raise HTTPResponse(boss_response.read(),
                               status=boss_response.status)
github iwatake2222 / RaspberryPiControllerQtPython / Server / index.py View on Github external
def GSensorIf():
	var = request.json
	# print (var)
	xyz = GSensor()
	retBody = {
		"ret": "ok",
		"x": xyz[0],
		"y": xyz[1],
		"z": xyz[2],
	}
	r = HTTPResponse(status=200, body=retBody)
	r.set_header('Content-Type', 'application/json')
	return r
github conan-io / conan / conans / server / rest / bottle_plugins / return_handler.py View on Github external
def wrapper(*args, **kwargs):
            """ Capture possible exceptions to manage the return """
            try:
                # The encoding from browsers is utf-8, so we assume it
                for key, value in kwargs.items():
                    if isinstance(value, str):
                        kwargs[key] = value
                return callback(*args, **kwargs)  # kwargs has :xxx variables from url
            except HTTPResponse:
                raise
            except ConanException as excep:
                return get_response_from_exception(excep, self.exception_mapping)
            except Exception as e:
                logger.error(e)
                logger.error(traceback.print_exc())
                return get_response_from_exception(e, self.exception_mapping)
github ralphwetzel / theonionbox / theonionbox / tob / static.py View on Github external
if filename in session['scripts'] or filename in session['stylesheets']:

            if filename in self.files:
                f = self.files[filename]

                if f['file'] in session:
                    file = session[f['file']]

                    # 3.0.4
                    session[f['file']] = None

                    if file is not None:

                        headers = {'Content-Type': '{}; charset=UTF-8'.format(self.mime_types[f['mime']])}
                        return HTTPResponse(file, **headers)

        # This happens as well when the file is requested more than once!
        raise HTTPError(404)