本文整理汇总了Python中cherrypy.HTTPError方法的典型用法代码示例。如果您正苦于以下问题:Python cherrypy.HTTPError方法的具体用法?Python cherrypy.HTTPError怎么用?Python cherrypy.HTTPError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cherrypy
的用法示例。
在下文中一共展示了cherrypy.HTTPError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: set_response
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def set_response(self):
"""Modify cherrypy.response status, headers, and body to represent
self.
CherryPy uses this internally, but you can also use it to create an
HTTPError object and set its output without *raising* the exception.
"""
response = cherrypy.serving.response
clean_headers(self.code)
# In all cases, finalize will be called after this method,
# so don't bother cleaning up response values here.
response.status = self.status
tb = None
if cherrypy.serving.request.show_tracebacks:
tb = format_exc()
response.headers.pop('Content-Length', None)
content = self.get_error_page(self.status, traceback=tb,
message=self._message)
response.body = content
_be_ie_unfriendly(self.code)
示例2: decode_entity
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def decode_entity(self, value):
"""Return a given byte encoded value as a string"""
for charset in self.attempt_charsets:
try:
value = value.decode(charset)
except UnicodeDecodeError:
pass
else:
self.charset = charset
return value
else:
raise cherrypy.HTTPError(
400,
'The request entity could not be decoded. The following '
'charsets were attempted: %s' % repr(self.attempt_charsets)
)
示例3: run
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def run(self):
request = cherrypy.serving.request
response = cherrypy.serving.response
path = request.path_info
if path.endswith('login_screen'):
self._debug_message('routing %(path)r to login_screen', locals())
response.body = self.login_screen()
return True
elif path.endswith('do_login'):
if request.method != 'POST':
response.headers['Allow'] = 'POST'
self._debug_message('do_login requires POST')
raise cherrypy.HTTPError(405)
self._debug_message('routing %(path)r to do_login', locals())
return self.do_login(**request.params)
elif path.endswith('do_logout'):
if request.method != 'POST':
response.headers['Allow'] = 'POST'
raise cherrypy.HTTPError(405)
self._debug_message('routing %(path)r to do_logout', locals())
return self.do_logout(**request.params)
else:
self._debug_message('No special path, running do_check')
return self.do_check()
示例4: qvalue
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def qvalue(self):
'The qvalue, or priority, of this value.'
val = self.params.get('q', '1')
if isinstance(val, HeaderElement):
val = val.value
try:
return float(val)
except ValueError as val_err:
"""Fail client requests with invalid quality value.
Ref: https://github.com/cherrypy/cherrypy/issues/1370
"""
raise cherrypy.HTTPError(
400,
'Malformed HTTP header: `{}`'.
format(str(self)),
) from val_err
示例5: setup_server
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def setup_server():
class Root:
@cherrypy.expose
def resource(self):
return 'Oh wah ta goo Siam.'
@cherrypy.expose
def fail(self, code):
code = int(code)
if 300 <= code <= 399:
raise cherrypy.HTTPRedirect([], code)
else:
raise cherrypy.HTTPError(code)
@cherrypy.expose
# In Python 3, tools.encode is on by default
@cherrypy.config(**{'tools.encode.on': True})
def unicoded(self):
return ntou('I am a \u1ee4nicode string.', 'escape')
conf = {'/': {'tools.etags.on': True,
'tools.etags.autotags': True,
}}
cherrypy.tree.mount(Root(), config=conf)
示例6: get_body
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def get_body(self, text=False):
"""
Get content body of received request header
:return:
"""
cl = cherrypy.request.headers.get('Content-Length', 0)
if cl == 0:
# cherrypy.reponse.headers["Status"] = "400"
# return 'Bad request'
raise cherrypy.HTTPError(status=411)
rawbody = cherrypy.request.body.read(int(cl))
self.logger.debug("ServicesController(): get_body(): rawbody = {}".format(rawbody))
try:
if text:
params = rawbody.decode('utf-8')
else:
params = json.loads(rawbody.decode('utf-8'))
except Exception as e:
self.logger.warning("ServicesController(): get_body(): Exception {}".format(e))
return None
return params
示例7: get_body
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def get_body(self):
"""
Get content body of received request header
:return:
"""
cl = cherrypy.request.headers.get('Content-Length', 0)
if cl == 0:
# cherrypy.reponse.headers["Status"] = "400"
# return 'Bad request'
raise cherrypy.HTTPError(status=411)
rawbody = cherrypy.request.body.read(int(cl))
self.logger.debug("PluginController(): ___(): rawbody = {}".format(rawbody))
try:
params = json.loads(rawbody.decode('utf-8'))
except Exception as e:
self.logger.warning("PluginController(): ___(): Exception {}".format(e))
return None
return params
示例8: save_scenes_config
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def save_scenes_config(self, filename):
"""
Save scene configuration
:return: status dict
"""
params = None
params = self.get_body(text=True)
if params is None:
self.logger.warning("FilesController.save_scenes_config(): Bad, request")
raise cherrypy.HTTPError(status=411)
self.logger.debug("FilesController.save_scenes_config(): '{}'".format(params))
filename = os.path.join(self.scenes_dir, filename + '.yaml')
read_data = None
with open(filename, 'w') as f:
f.write(params)
result = {"result": "ok"}
return json.dumps(result)
示例9: evalcheck
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def evalcheck(self):
"""
Check syntax of eval expression
:return: status dict
"""
params = self.get_body(text=False)
if params is None:
self.logger.warning("ServicesController(): evalcheck(): Bad, request")
raise cherrypy.HTTPError(status=411)
self.logger.info("ServicesController(): evalcheck(): {}".format(params))
expanded_code, eval_result = self.eval_syntax_checker(params['expression'], params['relative_to'])
result_type = str(type(eval_result))
if result_type.startswith("<class '"):
result_type = result_type[len("<class '"):]
result_type = result_type[:-2]
result = {'expression': expanded_code, 'result': eval_result, 'type': result_type}
# return json.dumps({'expression': 'Expandierter Ausdruck (Antwort vom Server)', 'result': '42 (Antwort vom Server)'})
return json.dumps(result)
# ======================================================================
# /api/server/yamlcheck
#
示例10: yamlcheck
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def yamlcheck(self):
"""
Check syntax of YAML configuration
:return: status dict
"""
params = self.get_body(text=True)
if params is None:
self.logger.warning("ServicesController(): yamlcheck(): Bad, request")
raise cherrypy.HTTPError(status=411)
self.logger.info("ServicesController(): yamlcheck(): '{}'".format(params))
return self.yaml_syntax_checker(params)
# ======================================================================
# /api/server/yamlconvert
#
示例11: sensors
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def sensors(self, start, stop, step, name):
try:
start = to_timestamp(start)
stop = to_timestamp(stop)
with self.storage.lock:
data = self.storage.data[name]
except Exception:
logger.exception("During parse input data")
raise cherrypy.HTTPError("Wrong date format")
if step != 1000:
raise cherrypy.HTTPError("Step must be equals to 1s")
num = stop - start
if len(data) > num:
data = data[-num:]
else:
data = [0] * (num - len(data)) + data
return data
示例12: digest_auth
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def digest_auth(realm, users, debug=False):
"""If auth fails, raise 401 with a digest authentication header.
realm
A string containing the authentication realm.
users
A dict of the form: {username: password} or a callable returning
a dict.
"""
if check_auth(users, realm=realm):
if debug:
cherrypy.log('Auth successful', 'TOOLS.DIGEST_AUTH')
return
# inform the user-agent this path is protected
cherrypy.serving.response.headers[
'www-authenticate'] = httpauth.digestAuth(realm)
raise cherrypy.HTTPError(
401, "You are not authorized to access that resource")
示例13: run
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def run(self, point):
"""Execute all registered Hooks (callbacks) for the given point."""
exc = None
hooks = self[point]
hooks.sort()
for hook in hooks:
# Some hooks are guaranteed to run even if others at
# the same hookpoint fail. We will still log the failure,
# but proceed on to the next hook. The only way
# to stop all processing from one of these hooks is
# to raise SystemExit and stop the whole server.
if exc is None or hook.failsafe:
try:
hook()
except (KeyboardInterrupt, SystemExit):
raise
except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
cherrypy.InternalRedirect):
exc = sys.exc_info()[1]
except:
exc = sys.exc_info()[1]
cherrypy.log(traceback=True, severity=40)
if exc:
raise exc
示例14: process_query_string
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def process_query_string(self):
"""Parse the query string into Python structures. (Core)"""
try:
p = httputil.parse_query_string(
self.query_string, encoding=self.query_string_encoding)
except UnicodeDecodeError:
raise cherrypy.HTTPError(
404, "The given query string could not be processed. Query "
"strings for this resource must be encoded with %r." %
self.query_string_encoding)
# Python 2 only: keyword arguments must be byte strings (type 'str').
if not py3k:
for key, value in p.items():
if isinstance(key, unicode):
del p[key]
p[key.encode(self.query_string_encoding)] = value
self.params.update(p)
示例15: decode_entity
# 需要导入模块: import cherrypy [as 别名]
# 或者: from cherrypy import HTTPError [as 别名]
def decode_entity(self , value):
"""Return a given byte encoded value as a string"""
for charset in self.attempt_charsets:
try:
value = value.decode(charset)
except UnicodeDecodeError:
pass
else:
self.charset = charset
return value
else:
raise cherrypy.HTTPError(
400,
'The request entity could not be decoded. The following '
'charsets were attempted: %s' % repr(self.attempt_charsets)
)