Python bottle.response.status() Examples

The following are 30 code examples of bottle.response.status(). 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.response , or try the search function .
Example #1
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def backend_info():
	api_auth = _authenticate()

	# Only Admin can do this
	if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	i = {}
	i["redis_connection"] = {}
	i["redis_connection"]["host"] = redis_host
	i["redis_connection"]["port"] = redis_port
	i["redis_dbsize"] = rc.dbsize()
	i["redis_client_list"] = rc.client_list()
	i["redis_info"] = rc.info()

	return(i)

# Trigger Redis Save 
Example #2
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def get_user_details(id):
	api_auth = _authenticate()

	# Only Admin can do this
	if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	# Read from Redis
	try:
		user_record = json.loads(rc.get("USER:"+str(id)))
	except:
		response.status = 404
		return dict({"info":"Not found."})

	user_out = {}
	user_out["username"] = user_record["username"]
	user_out["quota"] = user_record["quota"]

	return(dict(user_out))

# Set Quota for User 
Example #3
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def delete_user(id):
	api_auth = _authenticate()

	# Only Admin can do this
	if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	# Do not allow deleting admin
	if id == 0:
		response.status = 400
		return dict({"info":"Cannot delete admin user."})

	# Does the user exist?
	if rc.get("USER:"+str(id)) == None:
		response.status = 404
		return dict({"info":"Not found."})

	# Delete user record
	rc.delete("USER:"+str(id))
	return(dict(info="user deleted"))

# List All Users 
Example #4
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def list_user():
	api_auth = _authenticate()

	# Only Admin can do this
	if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	output = []
	user_list = rc.scan_iter("USER:*")
	for user in user_list:
		user_record = json.loads(rc.get(user))
		user_out = {}
		user_out["id"] = user[5:]
		user_out["username"] = user_record["username"]
		user_out["quota"] = user_record["quota"]
		output.append(user_out)

	return(dict(users=output))

# Change Admin Password 
Example #5
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def set_admin_password():
	api_auth = _authenticate()

	# Only Admin can do this
	if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
		response.status = 401
		return dict({"info":"Unauthorized."})

	try:
		payload = json.load(request.body)
		new_password = payload["password"]
	except:
		response.status = 400
		return dict({"info":"No valid JSON found in post body or mandatory fields missing."})

	# Read record for admin user
	admin_record = json.loads(rc.get("USER:0"))
	admin_record["hash"] = _get_password_hash(new_password)
	rc.set("USER:0", json.dumps(admin_record, ensure_ascii=False))

	return(dict(info="updated"))

# Read Key 
Example #6
Source File: bottle3.py    From pyFileFixity with MIT License 6 votes vote down vote up
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)] 
Example #7
Source File: api2.py    From codex-backend with MIT License 6 votes vote down vote up
def get_metadata():
    if request.query.file_hash == '':
        response.status = 400
        return jsonize({'message': 'file_hash parameter is missing'})
    file_hash = clean_hash(request.query.file_hash)
    if not valid_hash(file_hash):
        response.status = 400
        return jsonize({'message': 'Invalid hash format (use MD5, SHA1 or SHA2)'})
    file_hash = get_file_id(file_hash)
    if file_hash is None:
        response.status = 404
        return jsonize({'message': 'Metadata not found in the database'})

    mdc = MetaController()
    res = mdc.read(file_hash)
    if res is None:
        log_event("metadata", file_hash)
    return dumps(change_date_to_str(res)) 
Example #8
Source File: bottle2.py    From pyFileFixity with MIT License 6 votes vote down vote up
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)] 
Example #9
Source File: bambleweeny.py    From bambleweeny with MIT License 6 votes vote down vote up
def get_token():
	# Get JSON Payload
	try:
		payload = json.load(request.body)
		username = payload["username"]
		password = payload["password"]
		pwhash = _get_password_hash(password)
	except:
		response.status = 400
		return dict({"message":"No valid JSON found in post body or mandatory fields missing."})

	user_list = rc.scan_iter("USER:*")
	for user in user_list:
		user_record = json.loads(rc.get(user))
		if user_record["username"] == username and user_record["hash"] == pwhash:
			user_token = _issue_token(user=username, id=user[5:], expiry=token_expiry_seconds)
			if 'raw' in request.query:
				return(user_token)
			else:
				return(dict(token_type="bearer", access_token=user_token))

	response.status = 401
	return(dict(info="could not authorize user"))

# Test Auth Token 
Example #10
Source File: smserverlogic.py    From service-manager with Apache License 2.0 6 votes vote down vote up
def process_request(self):

        if not self.server.is_running(self.test_id):
            raise BadRequestException("Invalid test id (or already stopped): %s" % self.test_id)

        self._log("Stopping test")

        drop_databases = self.json_body.get("dropDatabases", True)

        if type(drop_databases) is not bool:
            raise self._bad_request_exception("dropDatabases parameter must be boolean (value was: %s)" % drop_databases)

        errors = self._stop_services(drop_databases)

        if errors:
            self._log("Completed stopping services - errors occurred: %s" % str(errors))
            response.status = 500
            return json.dumps({"statusCode": 500, "errorMessage": errors})
        else:
            self._log("Successfully stopped services")
            response.status = 204 
Example #11
Source File: test_bottle.py    From aws-xray-sdk-python with Apache License 2.0 6 votes vote down vote up
def test_custom_client_error():
    path = '/client_error'
    try:
        app.get(path)
    except Exception:
        pass
    segment = recorder.emitter.pop()
    assert not segment.in_progress
    assert segment.error

    response = segment.http['response']
    assert response['status'] == 400
    exception = segment.cause['exceptions'][0]
    assert exception.type == 'CustomError'

    request = segment.http['request']
    assert request['method'] == 'GET'
    assert request['url'] == BASE_URL.format(path) 
Example #12
Source File: test_bottle.py    From aws-xray-sdk-python with Apache License 2.0 6 votes vote down vote up
def test_error():
    path = '/error'
    try:
        app.get(path, extra_environ={'HTTP_X_FORWARDED_FOR': '192.168.0.0'})
    except Exception:
        pass
    segment = recorder.emitter.pop()
    assert not segment.in_progress
    assert segment.error

    request = segment.http['request']
    response = segment.http['response']
    assert request['method'] == 'GET'
    assert request['url'] == BASE_URL.format(path)
    assert request['client_ip'] == '192.168.0.0'
    assert response['status'] == 404 
Example #13
Source File: bottle.py    From annotated-py-bottle with MIT License 6 votes vote down vote up
def error_default(exception):
    status = response.status
    name = HTTP_CODES.get(status, 'Unknown').title()
    url = request.path
    """If an exception is thrown, deal with it and present an error page."""
    yield template('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' + \
                   '<html><head><title>Error {{status}}: {{msg}}</title>' + \
                   '</head><body><h1>Error {{status}}: {{msg}}</h1>' + \
                   '<p>Sorry, the requested URL {{url}} caused an error.</p>',
                   status=status,
                   msg=name,
                   url=url
                   )
    if hasattr(exception, 'output'):
        yield exception.output
    yield '</body></html>' 
Example #14
Source File: web.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
def jsonify(fn):
    @ft.wraps(fn)
    def inner(*a, **kw):
        response.content_type = 'application/json'
        try:
            data = fn(*a, **kw)
        except HTTPError as e:
            response.status = e.status_code
            data = {'errors': [e.body]}
        except schema.Error as e:
            response.status = 400
            data = {'errors': e.errors, 'schema': e.schema}
        except Exception as e:
            log.exception(e)
            response.status = 500
            data = {'errors': [str(e)]}
        return json.dumps(data or {}, indent=2, ensure_ascii=False)
    return inner 
Example #15
Source File: app.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def get_config():
    """Returns JavaScript code to set client-side configuration values

    :status 200: no error
    :status 400: invalid referer
    :>json object config: the configuration values

    """
    response.set_header('Content-Type', 'application/javascript')
    for key, value in [
            ("notesbase", config.WEB_NOTES_BASE),
            ("dflt_limit", config.WEB_LIMIT),
            ("warn_dots_count", config.WEB_WARN_DOTS_COUNT),
            ("publicsrv", config.WEB_PUBLIC_SRV),
            ("uploadok", config.WEB_UPLOAD_OK),
            ("flow_time_precision", config.FLOW_TIME_PRECISION),
            ("version", VERSION),
    ]:
        yield "config.%s = %s;\n" % (key, json.dumps(value))


#
# /nmap/
# 
Example #16
Source File: app.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
def get_nmap_count(subdb):
    """Get special values from Nmap & View databases

    :param str subdb: database to query (must be "scans" or "view")
    :query str q: query (including limit/skip and sort)
    :query str callback: callback to use for JSONP results
    :status 200: no error
    :status 400: invalid referer
    :>json int: count

    """
    subdb = db.view if subdb == 'view' else db.nmap
    flt_params = get_nmap_base(subdb)
    count = subdb.count(flt_params.flt)
    if flt_params.callback is None:
        return "%d\n" % count
    return "%s(%d);\n" % (flt_params.callback, count) 
Example #17
Source File: web.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
def login():
    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'username': {'type': 'string'},
            'password': {'type': 'string'},
            'timezone': {'type': 'string', 'enum': all_timezones},
            'theme': {'type': 'string', 'default': 'base'}
        },
        'required': ['username', 'password', 'timezone']
    })

    try:
        local.connect(data['username'], data['password'])
    except imap.Error as e:
        response.status = 400
        return {'errors': ['Authentication failed.'], 'details': str(e)}

    del data['password']
    request.session.update(data)
    return {} 
Example #18
Source File: web.py    From mailur with GNU General Public License v3.0 6 votes vote down vote up
def fetch_avatars(hashes, size=20, default='identicon', b64=True):
    def _avatar(hash):
        if hash in cache:
            return cache[hash]
        res = urllib.request.urlopen(get_gravatar_url(hash, size, default))
        result = hash, res.read() if res.status == 200 else None
        cache[hash] = result
        return result

    if not hasattr(fetch_avatars, 'cache'):
        fetch_avatars.cache = {}
    key = (size, default)
    fetch_avatars.cache.setdefault(key, {})
    cache = fetch_avatars.cache[key]

    pool = ThreadPool(20)
    res = pool.map(_avatar, hashes)
    return [(i[0], base64.b64encode(i[1]) if b64 else i[1]) for i in res if i] 
Example #19
Source File: compliant_api.py    From maloja with GNU General Public License v3.0 6 votes vote down vote up
def handle(path,keys):
	print("API request: " + str(path))
	print("Keys:")
	for k in keys:
		print("\t",k,":",keys.get(k))


	if len(path)>1 and (path[0],path[1]) in handlers:
		handler = handlers[(path[0],path[1])]
		path = path[2:]
		try:
			response.status,result = handler.handle(path,keys)
		except:
			type = sys.exc_info()[0]
			response.status,result = handler.errors[type]
	else:
		result = {"error":"Invalid scrobble protocol"}
		response.status = 500


	print("Response: " + str(result))
	return result 
Example #20
Source File: Gateway.py    From EDDN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def upload():
    response.set_header("Access-Control-Allow-Origin", "*")
    try:
        # Body may or may not be compressed.
        message_body = get_decompressed_message()
    except zlib.error as exc:
        # Some languages and libs do a crap job zlib compressing stuff. Provide
        # at least some kind of feedback for them to try to get pointed in
        # the correct direction.
        response.status = 400
        logger.error("gzip error with %s: %s" % (get_remote_address(), exc.message))
        return exc.message
    except MalformedUploadError as exc:
        # They probably sent an encoded POST, but got the key/val wrong.
        response.status = 400
        logger.error("Error to %s: %s" % (get_remote_address(), exc.message))
        return exc.message

    statsCollector.tally("inbound")
    return parse_and_error_handle(message_body) 
Example #21
Source File: database.py    From maloja with GNU General Public License v3.0 6 votes vote down vote up
def test_server(key=None):
	response.set_header("Access-Control-Allow-Origin","*")
	if key is not None and not (checkAPIkey(key)):
		response.status = 403
		return "Wrong API key"

	elif db_rulestate:
		response.status = 204
		return
	else:
		response.status = 205
		return

	# 204	Database server is up and operational
	# 205	Database server is up, but DB is not fully built or is inconsistent
	# 403	Database server is up, but provided API key is not valid 
Example #22
Source File: bottle3.py    From pyFileFixity with MIT License 5 votes vote down vote up
def copy(self):
        ''' Returns a copy of self '''
        copy = Response(self.app)
        copy.status = self.status
        copy.headers = self.headers.copy()
        copy.content_type = self.content_type
        return copy 
Example #23
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def redirect(url, code=None):
    if not code:
        code = 303 if request.get('SERVER_PROTOCOL') == 'HTTP/1.1' else 302
    response.status = code
    response.body = ''
    response.set_header('Location', urllib.parse.urljoin(request.url, url))
    return response 
Example #24
Source File: bottle3.py    From pyFileFixity with MIT License 5 votes vote down vote up
def static_file(filename, root, guessmime=True, mimetype=None, download=False):
    """ Opens a file in a save way and returns a HTTPError object with status
        code 200, 305, 401 or 404. Sets Content-Type, Content-Length and
        Last-Modified header. Obeys If-Modified-Since header and HEAD requests.
    """
    root = os.path.abspath(root) + os.sep
    filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
    header = dict()

    if not filename.startswith(root):
        return HTTPError(401, "Access denied.")
    if not os.path.exists(filename) or not os.path.isfile(filename):
        return HTTPError(404, "File does not exist.")
    if not os.access(filename, os.R_OK):
        return HTTPError(401, "You do not have permission to access this file.")

    if not mimetype and guessmime:
        header['Content-Type'] = mimetypes.guess_type(filename)[0]
    else:
        header['Content-Type'] = mimetype if mimetype else 'text/plain'

    if download == True:
        download = os.path.basename(filename)
    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 "<date>; length=146"
        ims = parse_date(ims)
        if ims is not None and ims >= int(stats.st_mtime):
           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) 
Example #25
Source File: bottle3.py    From pyFileFixity with MIT License 5 votes vote down vote up
def redirect(url, code=303):
    """ Aborts execution and causes a 303 redirect """
    scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
    location = urljoin(request.url, urljoin(scriptname, url))
    raise HTTPResponse("", status=code, header=dict(Location=location)) 
Example #26
Source File: photobackup.py    From server-bottle with GNU General Public License v2.0 5 votes vote down vote up
def end(code, message):
    """ Aborts the request and returns the given error. """
    log.error(message)
    response.status = code
    response.content_type = 'application/json'
    return json.dumps({'error': message}) 
Example #27
Source File: task.py    From ifwechat with MIT License 5 votes vote down vote up
def task(event):
    b = request._get_body_string()
    data = json.loads(b)
    ifmaker = IfMaker(event, data.pop('key'))
    code, content = ifmaker.fetch(**data)
    response.status = code
    return content 
Example #28
Source File: api2.py    From codex-backend with MIT License 5 votes vote down vote up
def get_result_from_av():
    hash_id = request.query.file_hash
    if len(hash_id) == 0:
        response.status = 400
        return jsonize({'error': 4, 'error_message': 'file_hash parameter is missing.'})
    hash_id = clean_hash(hash_id)
    if not valid_hash(hash_id):
        return jsonize({'error': 5, 'error_message': 'Invalid hash format.'})
    if(len(hash_id) != 40):
        data = "1=" + str(hash_id)
        res = SearchModule.search_by_id(data, 1, [], True)
        if(len(res) == 0):
            response.status = 400
            return jsonize({'error': 6, 'error_message': 'File not found'})
        else:
            sha1 = res[0]["sha1"]
    else:
        sha1 = hash_id
    key_manager = KeyManager()

    if(key_manager.check_keys_in_secrets()):
        av_result = get_av_result(sha1, 'high')
    else:
        return jsonize({'error': 7, "error_message": "Error: VirusTotal API key missing from secrets.py file"})
    if(av_result.get('status') == "added"):
        return jsonize({"message": "AV scans downloaded."})
    elif(av_result.get('status') == "already_had_it"):
        return jsonize({"message": "File already have AV scans."})
    elif(av_result.get('status') == "not_found"):
        return jsonize({"error": 10, "error_message": "Not found on VT."})
    elif(av_result.get('status') == "no_key_available"):
        return jsonize({"error": 11, "error_message": "No key available right now. Please try again later."})
    else:
        logging.error("av_result for hash=" + str(sha1))
        logging.error("av_result=" + str(av_result))
        return jsonize({"error": 9, "error_message": "Cannot get analysis."}) 
Example #29
Source File: compliant_api.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def submit(self,pathnodes,keys):
		try:
			token = keys.get("Authorization").replace("token ","").replace("Token ","").strip()
		except:
			raise BadAuthException()

		if token not in database.allAPIkeys():
			raise InvalidAuthException()

		try:
			if keys["listen_type"] in ["single","import"]:
				payload = keys["payload"]
				for listen in payload:
					metadata = listen["track_metadata"]
					artiststr, titlestr = metadata["artist_name"], metadata["track_name"]
					#(artists,title) = cla.fullclean(artiststr,titlestr)
					try:
						timestamp = int(listen["listened_at"])
					except:
						timestamp = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())
					#database.createScrobble(artists,title,timestamp)
					scrobbletrack(artiststr,titlestr,timestamp)
					return 200,{"code":200,"status":"ok"}
			else:
				return 200,{"code":200,"status":"ok"}
		except:
			raise MalformedJSONException() 
Example #30
Source File: bottle3.py    From pyFileFixity with MIT License 5 votes vote down vote up
def apply(self, response):
        if self.headers:
            for key, value in self.headers.iterallitems():
                response.headers[key] = value
        response.status = self.status