本文整理汇总了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
示例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()
示例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()
示例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()
示例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()
示例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
示例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)
示例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)
示例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() }
示例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
示例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')