Python bottle.HTTPError() Examples
The following are 30
code examples of bottle.HTTPError().
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: web.py From CuckooSploit with GNU General Public License v3.0 | 7 votes |
def get_files(task_id): if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") files_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files") zip_file = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files.zip") with zipfile.ZipFile(zip_file, "w", compression=zipfile.ZIP_DEFLATED) as archive: root_len = len(os.path.abspath(files_path)) for root, dirs, files in os.walk(files_path): archive_root = os.path.abspath(root)[root_len:] for f in files: fullpath = os.path.join(root, f) archive_name = os.path.join(archive_root, f) archive.write(fullpath, archive_name, zipfile.ZIP_DEFLATED) if not os.path.exists(files_path): return HTTPError(code=404, output="Files not found") response.content_type = "application/zip" response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_%s(not_encrypted).zip" % (task_id)) return open(zip_file, "rb").read()
Example #2
Source File: main.py From bazarr with GNU General Public License v3.0 | 6 votes |
def custom_auth_basic(check): def decorator(func): def wrapper(*a, **ka): if settings.auth.type == 'basic': user, password = request.auth or (None, None) if user is None or not check(user, password): err = HTTPError(401, "Access denied") err.add_header('WWW-Authenticate', 'Basic realm="Bazarr"') return err return func(*a, **ka) else: return func(*a, **ka) return wrapper return decorator
Example #3
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def files_view(md5=None, sha256=None, sample_id=None): response = {} if md5: sample = db.find_sample(md5=md5) elif sha256: sample = db.find_sample(sha256=sha256) elif sample_id: sample = db.view_sample(sample_id) else: return HTTPError(400, "Invalid lookup term") if sample: response["sample"] = sample.to_dict() else: return HTTPError(404, "File not found") return jsonize(response)
Example #4
Source File: app.py From browsertrix with MIT License | 6 votes |
def get_params(): url = request.query.get('url') archive = request.query.get('archive') browser_type = request.query.get('browser', 'chrome') if not url: raise HTTPError(status=400, body='No url= specified') if archive not in theconfig['archives']: raise HTTPError(status=400, body='No archive {0}'.format(archive)) if not url.startswith(('http://', 'https://')): url = 'http://' + url return browser_type, archive, url
Example #5
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def tasks_delete(task_id): response = {} task = db.view_task(task_id) if task: if task.status == TASK_RUNNING: return HTTPError(500, "The task is currently being " "processed, cannot delete") if db.delete_task(task_id): delete_folder(os.path.join(CUCKOO_ROOT, "storage", "analyses", "%d" % task_id)) response["status"] = "OK" else: return HTTPError(500, "An error occurred while trying to " "delete the task") else: return HTTPError(404, "Task not found") return jsonize(response)
Example #6
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def tasks_view(task_id): response = {} task = db.view_task(task_id, details=True) if task: entry = task.to_dict() entry["guest"] = {} if task.guest: entry["guest"] = task.guest.to_dict() entry["errors"] = [] for error in task.errors: entry["errors"].append(error.message) entry["sample"] = {} if task.sample_id: sample = db.view_sample(task.sample_id) entry["sample"] = sample.to_dict() response["task"] = entry else: return HTTPError(404, "Task not found") return jsonize(response)
Example #7
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 6 votes |
def task_screenshots(task=0, screenshot=None): folder_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", str(task), "shots") if os.path.exists(folder_path): if screenshot: screenshot_name = "{0}.jpg".format(screenshot) screenshot_path = os.path.join(folder_path, screenshot_name) if os.path.exists(screenshot_path): # TODO: Add content disposition. response.content_type = "image/jpeg" return open(screenshot_path, "rb").read() else: return HTTPError(404, screenshot_path) else: zip_data = StringIO() with ZipFile(zip_data, "w", ZIP_STORED) as zip_file: for shot_name in os.listdir(folder_path): zip_file.write(os.path.join(folder_path, shot_name), shot_name) # TODO: Add content disposition. response.content_type = "application/zip" return zip_data.getvalue() else: return HTTPError(404, folder_path)
Example #8
Source File: web.py From mailur with GNU General Public License v3.0 | 6 votes |
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 #9
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_can_admin_coll(self, collection): """Assert currrent user has right to administrate collection. :param Collection collection: collection """ if not self.can_admin_coll(collection): raise HTTPError(404, 'No Admin Access')
Example #10
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_can_write_coll(self, collection): """Assert current user has right to modify collection. :param Collection collection: collection """ if not self.can_write_coll(collection): raise HTTPError(404, 'No Write Access') # for now, equivalent to is_owner(), but a different # permission, and may change
Example #11
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_can_read_coll(self, collection): """Assert current user has right to read collection. :param Collection collection: collection """ if not self.can_read_coll(collection): raise HTTPError(404, 'No Read Access')
Example #12
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_is_superuser(self): """Assert current user is superuser, i.e. has the role 'admin' (level 100).""" if not self.is_superuser(): raise HTTPError(404, 'No Access')
Example #13
Source File: webhook.py From squadron with MIT License | 5 votes |
def _raise(self, code, message): if self.log: self.log.error('Returning %s: %s', code, message) raise bottle.HTTPError(code, message)
Example #14
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 5 votes |
def pcap_get(task_id): file_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", "%d" % task_id, "dump.pcap") if os.path.exists(file_path): response.content_type = "application/octet-stream; charset=UTF-8" try: return open(file_path, "rb").read() except: return HTTPError(500, "An error occurred while reading PCAP") else: return HTTPError(404, "File not found")
Example #15
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_is_curr_user(self, user): """Assert given user is current user or current user is superuser. :param User user: user """ if not self.is_curr_user(user) and not self.is_superuser(): raise HTTPError(404, 'Only Valid for Current User')
Example #16
Source File: access.py From conifer with Apache License 2.0 | 5 votes |
def assert_can_read_list(self, blist): """Assert current user has right to read list. :param BookmarkList blist: list of bookmarks """ if not self.can_read_list(blist): raise HTTPError(404, 'No List Access')
Example #17
Source File: basecontroller.py From conifer with Apache License 2.0 | 5 votes |
def _raise_error(self, code, message='not_found'): result = {'error': message} #result.update(kwargs) response.status = code raise HTTPError(code, message, exception=result)
Example #18
Source File: service.py From eavatar-me with Apache License 2.0 | 5 votes |
def raise_unauthorized(desc=b'Authentication required.'): raise HTTPError(D.HTTP_STATUS_AUTH_REQUIRED, desc)
Example #19
Source File: http_utils.py From box-python-sdk with Apache License 2.0 | 5 votes |
def abort(code, message=None, headers=None): """ Abort a request and send a response with the given code, and optional message and headers. :raises: :class:`HTTPError` """ raise HTTPError(code, {'message': message}, headers=headers)
Example #20
Source File: api.py From CuckooSploit with GNU General Public License v3.0 | 5 votes |
def files_get(sha256): file_path = os.path.join(CUCKOO_ROOT, "storage", "binaries", sha256) if os.path.exists(file_path): response.content_type = "application/octet-stream; charset=UTF-8" return open(file_path, "rb").read() else: return HTTPError(404, "File not found")
Example #21
Source File: web.py From CuckooSploit with GNU General Public License v3.0 | 5 votes |
def get_pcap(task_id): if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") pcap_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "dump.pcap") if not os.path.exists(pcap_path): return HTTPError(code=404, output="PCAP not found") response.content_type = "application/vnd.tcpdump.pcap" response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_{0}.pcap".format(task_id)) return open(pcap_path, "rb").read()
Example #22
Source File: web.py From CuckooSploit with GNU General Public License v3.0 | 5 votes |
def view(task_id): if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") report_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "reports", "report.html") if not os.path.exists(report_path): return HTTPError(code=404, output="Report not found") return open(report_path, "rb").read().replace("<!-- BOTTLEREMOVEME", "").replace("BOTTLEREMOVEME --!>", "")
Example #23
Source File: web.py From CuckooSploit with GNU General Public License v3.0 | 5 votes |
def downlaod_report(task_id): if not task_id.isdigit(): return HTTPError(code=404, output="The specified ID is invalid") report_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "reports", "report.html") if not os.path.exists(report_path): return HTTPError(code=404, output="Report not found") response.content_type = "text/html" response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_{0}.html".format(task_id)) return open(report_path, "rb").read()
Example #24
Source File: test_bottle.py From aws-xray-sdk-python with Apache License 2.0 | 5 votes |
def test_server_error(): path = '/server_error' try: app.get(path) except Exception as e: pass segment = recorder.emitter.pop() assert not segment.in_progress assert segment.fault response = segment.http['response'] assert response['status'] == 503 exception = segment.cause['exceptions'][0] assert exception.type == 'HTTPError'
Example #25
Source File: test_bottle.py From aws-xray-sdk-python with Apache License 2.0 | 5 votes |
def faulty_server(): raise HTTPError(status=503, body='Service Unavailable')
Example #26
Source File: ibbottle.py From infrabox with MIT License | 5 votes |
def apply(self, callback, context): # Test if the original callback accepts a 'conn' keyword. # Ignore it if it does not need a database connection. args = inspect.getargspec(context['callback'])[0] if 'conn' not in args: return callback def wrapper(*args, **kwargs): for _ in range(0, 3): # Connect to the database conn = None try: conn = self.pool.getconn() except HTTPResponse, e: raise HTTPError(500, "Database Error", e) # Add the connection handle as a keyword argument. kwargs['conn'] = conn try: rv = callback(*args, **kwargs) return rv except HTTPError, e: raise except HTTPResponse, e: raise
Example #27
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 5 votes |
def verify_request(self, scopes=None): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" # Get the list of scopes try: scopes_list = scopes(bottle.request) except TypeError: scopes_list = scopes uri, http_method, body, headers = extract_params(bottle.request) valid, req = self._oauthlib.verify_request(uri, http_method, body, headers, scopes_list) # For convenient parameter access in the view add_params_to_request(bottle.request, { 'client': req.client, 'user': req.user, 'scopes': req.scopes }) if valid: return f(*args, **kwargs) # Framework specific HTTP 403 return HTTPError(403, "Permission denied") return wrapper return decorator
Example #28
Source File: ibbottle.py From InfraBox with Apache License 2.0 | 5 votes |
def apply(self, callback, context): # Test if the original callback accepts a 'conn' keyword. # Ignore it if it does not need a database connection. args = inspect.getargspec(context['callback'])[0] if 'conn' not in args: return callback def wrapper(*args, **kwargs): for _ in range(0, 3): # Connect to the database conn = None try: conn = self.pool.getconn() except HTTPResponse, e: raise HTTPError(500, "Database Error", e) # Add the connection handle as a keyword argument. kwargs['conn'] = conn try: rv = callback(*args, **kwargs) return rv except HTTPError, e: raise except HTTPResponse, e: raise
Example #29
Source File: routes.py From PTVS-Samples with Apache License 2.0 | 5 votes |
def details_post(key): """Handles voting. Validates input and updates the repository.""" try: choice_key = request.forms.get('choice', '') if choice_key: repository.increment_vote(key, choice_key) return redirect('/results/{0}'.format(key)) else: return details(key, 'Please make a selection.') except PollNotFound: raise HTTPError(404, "Poll does not exist.")
Example #30
Source File: routes.py From PTVS-Samples with Apache License 2.0 | 5 votes |
def details_get(key): """Renders the poll details page.""" try: return details(key, '') except PollNotFound: raise HTTPError(404, "Poll does not exist.")