当前位置: 首页>>代码示例>>Python>>正文


Python bottle.HTTPError方法代码示例

本文整理汇总了Python中bottle.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python bottle.HTTPError方法的具体用法?Python bottle.HTTPError怎么用?Python bottle.HTTPError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在bottle的用法示例。


在下文中一共展示了bottle.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_params

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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 
开发者ID:ikreymer,项目名称:browsertrix,代码行数:19,代码来源:app.py

示例2: jsonify

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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 
开发者ID:naspeh,项目名称:mailur,代码行数:20,代码来源:web.py

示例3: get_files

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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() 
开发者ID:davidoren,项目名称:CuckooSploit,代码行数:24,代码来源:web.py

示例4: tasks_view

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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) 
开发者ID:davidoren,项目名称:CuckooSploit,代码行数:26,代码来源:api.py

示例5: tasks_delete

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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) 
开发者ID:davidoren,项目名称:CuckooSploit,代码行数:22,代码来源:api.py

示例6: files_view

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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) 
开发者ID:davidoren,项目名称:CuckooSploit,代码行数:20,代码来源:api.py

示例7: task_screenshots

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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) 
开发者ID:davidoren,项目名称:CuckooSploit,代码行数:26,代码来源:api.py

示例8: custom_auth_basic

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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 
开发者ID:morpheus65535,项目名称:bazarr,代码行数:18,代码来源:main.py

示例9: download

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
def download():
    browser_type, archive, url = get_params()

    response_key = get_cache_key(archive, browser_type, url)

    result = rc.get(response_key)
    if not result:
        raise HTTPError(status=404, body='Url Not Archived')

    result = json.loads(result)
    if not 'download_url' in result:
        raise HTTPError(status=404, body='Download Not Available')

    headers = {}
    session = result.get('download_session')

    if session:
        headers['Cookie'] = session

    r = requests.get(result['download_url'],
                     headers=headers,
                     stream=True)

    if r.status_code != 200:
        raise HTTPError(status=400, body='Invalid Download Result: {0} {1}'.format(r.status_code, r.reason))

    pass_headers = ('Content-Disposition', 'Content-Length', 'Content-Type')

    for h in pass_headers:
        response.set_header(h, r.headers.get(h))

    response.body = r.iter_content()
    return response 
开发者ID:ikreymer,项目名称:browsertrix,代码行数:35,代码来源:app.py

示例10: results

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
def results(key):
    """Renders the results page."""
    try:
        poll = repository.get_poll(key)
        poll.calculate_stats()
        return dict(
            title='Results',
            year=datetime.now().year,
            poll=poll,
        )
    except PollNotFound:
        raise HTTPError(404, "Poll does not exist.") 
开发者ID:microsoft,项目名称:PTVS-Samples,代码行数:14,代码来源:routes.py

示例11: details_get

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
def details_get(key):
    """Renders the poll details page."""
    try:
        return details(key, '')
    except PollNotFound:
        raise HTTPError(404, "Poll does not exist.") 
开发者ID:microsoft,项目名称:PTVS-Samples,代码行数:8,代码来源:routes.py

示例12: details_post

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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.") 
开发者ID:microsoft,项目名称:PTVS-Samples,代码行数:13,代码来源:routes.py

示例13: apply

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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 
开发者ID:SAP,项目名称:InfraBox,代码行数:28,代码来源:ibbottle.py

示例14: verify_request

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
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 
开发者ID:Refinitiv,项目名称:bottle-oauthlib,代码行数:30,代码来源:oauth2.py

示例15: faulty_server

# 需要导入模块: import bottle [as 别名]
# 或者: from bottle import HTTPError [as 别名]
def faulty_server():
    raise HTTPError(status=503, body='Service Unavailable') 
开发者ID:aws,项目名称:aws-xray-sdk-python,代码行数:4,代码来源:test_bottle.py


注:本文中的bottle.HTTPError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。