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


Python web.HTTPError方法代码示例

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


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

示例1: generate_http_error

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def generate_http_error(status_code, exc_cls, exc_msg):
    """
    utitily function to generate a complete HTTP error response.
    :param status_code: The HTTP status code to generate a response for.
    :param exc_cls: The name of the exception class to send with the response.
    :param exc_msg: The error message.
    :returns: a web.py HTTP response object.
    """
    status = codes[status_code]
    data = {'ExceptionClass': exc_cls,
            'ExceptionMessage': exc_msg}
    # Truncate too long exc_msg
    if len(str(exc_msg)) > 15000:
        exc_msg = str(exc_msg)[:15000]
    headers = {'Content-Type': 'application/octet-stream',
               'ExceptionClass': exc_cls,
               'ExceptionMessage': clean_headers(exc_msg)}
    try:
        return HTTPError(status, headers=headers, data=render_json(**data))
    except Exception:
        print({'Content-Type': 'application/octet-stream', 'ExceptionClass': exc_cls, 'ExceptionMessage': str(exc_msg).strip()})
        raise 
开发者ID:rucio,项目名称:rucio,代码行数:24,代码来源:utils.py

示例2: put

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def put(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        bucket_dir = os.path.abspath(os.path.join(
            self.application.directory, bucket))
        if not bucket_dir.startswith(self.application.directory) or \
           not os.path.isdir(bucket_dir):
            raise web.HTTPError(404)
        path = self._object_path(bucket, object_name)
        if not path.startswith(bucket_dir) or os.path.isdir(path):
            raise web.HTTPError(403)
        directory = os.path.dirname(path)
        if not os.path.exists(directory):
            os.makedirs(directory)
        object_file = open(path, "w")
        object_file.write(self.request.body)
        object_file.close()
        self.finish() 
开发者ID:omererdem,项目名称:honeything,代码行数:19,代码来源:s3server.py

示例3: GET

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def GET(self, courseid, taskid, path):  # pylint: disable=arguments-differ
        """ GET request """
        try:
            course = self.course_factory.get_course(courseid)
            if not self.user_manager.course_is_open_to_user(course):
                return handle_course_unavailable(self.app.get_homepath(), self.template_helper, self.user_manager, course)

            path_norm = posixpath.normpath(urllib.parse.unquote(path))

            if taskid == "$common":
                public_folder = course.get_fs().from_subfolder("$common").from_subfolder("public")
            else:

                task = course.get_task(taskid)
                if not self.user_manager.task_is_visible_by_user(task):  # ignore LTI check here
                    return self.template_helper.get_renderer().task_unavailable()

                public_folder = task.get_fs().from_subfolder("public")
            (method, mimetype_or_none, file_or_url) = public_folder.distribute(path_norm, False)

            if method == "local":
                web.header('Content-Type', mimetype_or_none)
                return file_or_url
            elif method == "url":
                raise web.redirect(file_or_url)
            else:
                raise web.notfound()
        except web.HTTPError as error_or_redirect:
            raise error_or_redirect
        except:
            if web.config.debug:
                raise
            else:
                raise web.notfound() 
开发者ID:UCL-INGI,项目名称:INGInious,代码行数:36,代码来源:tasks.py

示例4: delete

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def delete(self, bucket_name):
        path = os.path.abspath(os.path.join(
            self.application.directory, bucket_name))
        if not path.startswith(self.application.directory) or \
           not os.path.isdir(path):
            raise web.HTTPError(404)
        if len(os.listdir(path)) > 0:
            raise web.HTTPError(403)
        os.rmdir(path)
        self.set_status(204)
        self.finish() 
开发者ID:omererdem,项目名称:honeything,代码行数:13,代码来源:s3server.py

示例5: get

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def get(self, bucket, object_name):
        object_name = urllib.unquote(object_name)
        path = self._object_path(bucket, object_name)
        if not path.startswith(self.application.directory) or \
           not os.path.isfile(path):
            raise web.HTTPError(404)
        info = os.stat(path)
        self.set_header("Content-Type", "application/unknown")
        self.set_header("Last-Modified", datetime.datetime.utcfromtimestamp(
            info.st_mtime))
        object_file = open(path, "r")
        try:
            self.finish(object_file.read())
        finally:
            object_file.close() 
开发者ID:omererdem,项目名称:honeything,代码行数:17,代码来源:s3server.py

示例6: csrf_protected

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def csrf_protected(f):
    def decorated(*args, **kwargs):
        inp = web.input()
        if not ('csrf_token' in inp and inp.csrf_token == session.pop('csrf_token', None)):
            raise web.HTTPError(
                "400 Bad request",
                {'content-type':'text/html'},
                """Cross-site request forgery (CSRF) attempt (or stale browser form). <a href="">Back to the form</a>.""")
        return f(*args, **kwargs)
    return decorated 
开发者ID:ab77,项目名称:netflix-proxy,代码行数:12,代码来源:auth.py

示例7: __init__

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def __init__(self, msg):
        status = '500 Internal Server Error'
        headers = { 'Content-Type': "text/html" }
        data = "<h1>DBFS Error</h1><p>%s</p>" % msg
        web.HTTPError.__init__(self, status, headers, data) 
开发者ID:bobintetley,项目名称:asm3,代码行数:7,代码来源:dbfs.py

示例8: __init__

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def __init__(self, msg):
        self.msg = msg
        status = '500 Internal Server Error'
        headers = { 'Content-Type': "text/html" }
        data = "<h1>Validation Error</h1><p>%s</p>" % msg
        if "headers" not in web.ctx: web.ctx.headers = []
        web.HTTPError.__init__(self, status, headers, data) 
开发者ID:bobintetley,项目名称:asm3,代码行数:9,代码来源:utils.py

示例9: post_data

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def post_data(url, data, contenttype = "", httpmethod = "", headers = {}):
    """
    Posts data (str or bytes) to a URL as the body
    httpmethod: POST by default.
    Returns dict of requestheaders (dict), requestbody (bytes), headers (str), response (str) and status (int)
    """
    # PYTHON3
    # Separate implementations here due to change in HTTPMessage response object
    # between 2 and 3. (.headers disappears to be replaced with as_string() due to new superclass)
    if sys.version_info[0] > 2:
        try:
            if contenttype != "": headers["Content-Type"] = contenttype
            if isinstance(data, str): data = str2bytes(data)
            req = urllib2.Request(url, data, headers)
            if httpmethod != "": req.get_method = lambda: httpmethod
            resp = urllib2.urlopen(req)
            return { "requestheaders": headers, "requestbody": data, "headers": resp.info().as_string(), "response": bytes2str(resp.read()), "status": resp.getcode() }
        except urllib2.HTTPError as e:
            return { "requestheaders": headers, "requestbody": data, "headers": e.info().as_string(), "response": bytes2str(e.read()), "status": e.getcode() }
    # PYTHON2
    else:
        try:
            if contenttype != "": headers["Content-Type"] = contenttype
            req = urllib2.Request(url, data, headers)
            if httpmethod != "": req.get_method = lambda: httpmethod
            resp = urllib2.urlopen(req)
            return { "requestheaders": headers, "requestbody": data, "headers": resp.info().headers, "response": encode_html(cunicode(resp.read())), "status": resp.getcode() }
        except urllib2.HTTPError as e:
            return { "requestheaders": headers, "requestbody": data, "headers": e.info().headers, "response": encode_html(cunicode(e.read())), "status": e.getcode() } 
开发者ID:bobintetley,项目名称:asm3,代码行数:31,代码来源:utils.py

示例10: __init__

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def __init__(self, url, absolute=False):

        status = '303 See Other'
        newloc = url

        home = web.ctx.environ['HTTP_ORIGIN']
        newloc = urlparse.urljoin(home, url)
        logger.info('seeother: %s', newloc)
        headers = {
            'Content-Type': 'text/html',
            'Location': newloc
        }
        web.webapi.HTTPError.__init__(self, status, headers, "")
        pass 
开发者ID:opennumber,项目名称:opennumber,代码行数:16,代码来源:__init__.py

示例11: GET

# 需要导入模块: import web [as 别名]
# 或者: from web import HTTPError [as 别名]
def GET(self, *args, **kwargs):
        """
        """
        response = Response.internal_error()
        try:
            self.log_request()
            with models.Session() as orm:
                web.ctx.orm = orm
                response =  self.get(*args, **kwargs)
                return response
        except:
            logger.exception('BaseHandler failure:')
            status = '500 InternalError'
            headers = {'Content-Type': 'text/html'}
            raise web.HTTPError(status, headers, 'internal error') 
开发者ID:opennumber,项目名称:opennumber,代码行数:17,代码来源:__init__.py


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