當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。