本文整理汇总了Python中werkzeug.exceptions方法的典型用法代码示例。如果您正苦于以下问题:Python werkzeug.exceptions方法的具体用法?Python werkzeug.exceptions怎么用?Python werkzeug.exceptions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块werkzeug的用法示例。
在下文中一共展示了werkzeug.exceptions方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: abort
点赞 6
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def abort(status, *args, **kwargs):
"""Raises an :py:exc:`HTTPException` for the given status code or WSGI
application::
abort(404) # 404 Not Found
abort(Response('Hello World'))
Can be passed a WSGI application or a status code. If a status code is
given it's looked up in the list of exceptions and will raise that
exception, if passed a WSGI application it will wrap it in a proxy WSGI
exception and raise that::
abort(404)
abort(Response('Hello World'))
"""
return _aborter(status, *args, **kwargs)
开发者ID:Frank-qlu,项目名称:recruit,代码行数:19,
示例2: abort
点赞 6
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def abort(status, *args, **kwargs):
'''
Raises an :py:exc:`HTTPException` for the given status code or WSGI
application::
abort(404) # 404 Not Found
abort(Response('Hello World'))
Can be passed a WSGI application or a status code. If a status code is
given it's looked up in the list of exceptions and will raise that
exception, if passed a WSGI application it will wrap it in a proxy WSGI
exception and raise that::
abort(404)
abort(Response('Hello World'))
'''
return _aborter(status, *args, **kwargs)
开发者ID:ryfeus,项目名称:lambda-packs,代码行数:20,
示例3: dispatch
点赞 6
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def dispatch(self, controller, method):
params = dict(self.httprequest.args)
params.update(self.httprequest.form)
params.update(self.httprequest.files)
self.init(params)
akw = {}
for key, value in self.httprequest.args.iteritems():
if isinstance(value, basestring) and len(value) < 1024:
akw[key] = value
else:
akw[key] = type(value)
_logger.debug("%s --> %s.%s %r", self.httprequest.method, controller.__class__.__name__, method.__name__, akw)
try:
r = method(controller, self, **self.params)
except xmlrpclib.Fault, e:
r = werkzeug.exceptions.InternalServerError(cgi.escape(simplejson.dumps({
'code': 200,
'message': "OpenERP Server Error",
'data': {
'type': 'server_exception',
'fault_code': e.faultCode,
'debug': "Server %s\nClient %s" % (
e.faultString, traceback.format_exc())
}
})))
开发者ID:iw3hxn,项目名称:LibrERP,代码行数:27,
示例4: serialize_exception
点赞 6
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def serialize_exception(e):
tmp = {
"name": type(e).__module__ + "." + type(e).__name__ if type(e).__module__ else type(e).__name__,
"debug": traceback.format_exc(),
"message": ustr(e),
"arguments": e.args,
"exception_type": "internal_error"
}
if isinstance(e, odoo.exceptions.UserError):
tmp["exception_type"] = "user_error"
elif isinstance(e, odoo.exceptions.Warning):
tmp["exception_type"] = "warning"
elif isinstance(e, odoo.exceptions.RedirectWarning):
tmp["exception_type"] = "warning"
elif isinstance(e, odoo.exceptions.AccessError):
tmp["exception_type"] = "access_error"
elif isinstance(e, odoo.exceptions.MissingError):
tmp["exception_type"] = "missing_error"
elif isinstance(e, odoo.exceptions.AccessDenied):
tmp["exception_type"] = "access_denied"
elif isinstance(e, odoo.exceptions.ValidationError):
tmp["exception_type"] = "validation_error"
elif isinstance(e, odoo.exceptions.except_orm):
tmp["exception_type"] = "except_orm"
return tmp
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:27,
示例5: _handle_exception
点赞 6
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def _handle_exception(self, exception):
"""Called within an except block to allow converting exceptions
to abitrary responses. Anything returned (except None) will
be used as response."""
try:
return super(HttpRequest, self)._handle_exception(exception)
except SessionExpiredException:
redirect = None
req = request.httprequest
if req.method == 'POST':
request.session.save_request_data()
redirect = '/web/proxy/post{r.full_path}'.format(r=req)
elif not request.params.get('noredirect'):
redirect = req.url
if redirect:
query = werkzeug.urls.url_encode({
'redirect': redirect,
})
return werkzeug.utils.redirect('/web/login?%s' % query)
except werkzeug.exceptions.HTTPException as e:
return e
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:23,
示例6: not_found
点赞 5
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def not_found(self, description=None):
""" Helper for 404 response, return its result from the method
"""
return werkzeug.exceptions.NotFound(description)
开发者ID:iw3hxn,项目名称:LibrERP,代码行数:6,
示例7: replace_request_password
点赞 5
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def replace_request_password(args):
# password is always 3rd argument in a request, we replace it in RPC logs
# so it's easier to forward logs for diagnostics/debugging purposes...
if len(args) > 2:
args = list(args)
args[2] = '*'
return tuple(args)
# don't trigger debugger for those exceptions, they carry user-facing warnings
# and indications, they're not necessarily indicative of anything being
# *broken*
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:13,
示例8: _call_function
点赞 5
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def _call_function(self, *args, **kwargs):
request = self
if self.endpoint.routing['type'] != self._request_type:
msg = "%s, %s: Function declared as capable of handling request of type '%s' but called with a request of type '%s'"
params = (self.endpoint.original, self.httprequest.path, self.endpoint.routing['type'], self._request_type)
_logger.info(msg, *params)
raise werkzeug.exceptions.BadRequest(msg % params)
if self.endpoint_arguments:
kwargs.update(self.endpoint_arguments)
# Backward for 7.0
if self.endpoint.first_arg_is_req:
args = (request,) + args
# Correct exception handling and concurency retry
@service_model.check
def checked_call(___dbname, *a, **kw):
# The decorator can call us more than once if there is an database error. In this
# case, the request cursor is unusable. Rollback transaction to create a new one.
if self._cr:
self._cr.rollback()
self.env.clear()
result = self.endpoint(*a, **kw)
if isinstance(result, Response) and result.is_qweb:
# Early rendering of lazy responses to benefit from @service_model.check protection
result.flatten()
return result
if self.db:
return checked_call(self.db, *args, **kwargs)
return self.endpoint(*args, **kwargs)
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:34,
示例9: not_found
点赞 5
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def not_found(self, description=None):
""" Shortcut for a `HTTP 404
`_ (Not Found)
response
"""
return werkzeug.exceptions.NotFound(description)
#----------------------------------------------------------
# Controller and route registration
#----------------------------------------------------------
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:12,
示例10: init_app
点赞 5
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def init_app(app):
# install a universal error handler that will render errors based on the
# Accept header in the request
@app.errorhandler(Exception)
def exc_handler(error):
exc_type, exc_value, tb = sys.exc_info()
h = _get_handler()
return h.handle_exception(exc_type, exc_value, tb)
# always trap http exceptions; the HTML handler will render them
# as expected, but the JSON handler needs its chance, too
app.trap_http_exception = lambda e: True
# create a new subclass of the current json_encoder, that can handle
# encoding WSME types
old_json_encoder = app.json_encoder
class WSMEEncoder(old_json_encoder):
"""A mixin for JSONEncoder which can handle WSME types"""
def default(self, o):
if isinstance(o, wsme.types.Base):
return wsme.rest.json.tojson(type(o), o)
return old_json_encoder.default(self, o)
app.json_encoder = WSMEEncoder
开发者ID:mozilla,项目名称:build-relengapi,代码行数:29,
示例11: dispatch_rpc
点赞 4
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def dispatch_rpc(service_name, method, params):
""" Handle a RPC call.
This is pure Python code, the actual marshalling (from/to XML-RPC) is done
in a upper layer.
"""
try:
rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
if rpc_request_flag or rpc_response_flag:
start_time = time.time()
start_memory = 0
if psutil:
start_memory = memory_info(psutil.Process(os.getpid()))
if rpc_request and rpc_response_flag:
odoo.netsvc.log(rpc_request, logging.DEBUG, '%s.%s' % (service_name, method), replace_request_password(params))
threading.current_thread().uid = None
threading.current_thread().dbname = None
if service_name == 'common':
dispatch = odoo.service.common.dispatch
elif service_name == 'db':
dispatch = odoo.service.db.dispatch
elif service_name == 'object':
dispatch = odoo.service.model.dispatch
result = dispatch(method, params)
if rpc_request_flag or rpc_response_flag:
end_time = time.time()
end_memory = 0
if psutil:
end_memory = memory_info(psutil.Process(os.getpid()))
logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_memory / 1024, end_memory / 1024, (end_memory - start_memory)/1024)
if rpc_response_flag:
odoo.netsvc.log(rpc_response, logging.DEBUG, logline, result)
else:
odoo.netsvc.log(rpc_request, logging.DEBUG, logline, replace_request_password(params), depth=1)
return result
except NO_POSTMORTEM:
raise
except odoo.exceptions.DeferredException as e:
_logger.exception(odoo.tools.exception_to_unicode(e))
odoo.tools.debugger.post_mortem(odoo.tools.config, e.traceback)
raise
except Exception as e:
_logger.exception(odoo.tools.exception_to_unicode(e))
odoo.tools.debugger.post_mortem(odoo.tools.config, sys.exc_info())
raise
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:51,
示例12: __init__
点赞 4
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def __init__(self, *args):
super(JsonRequest, self).__init__(*args)
self.jsonp_handler = None
self.params = {}
args = self.httprequest.args
jsonp = args.get('jsonp')
self.jsonp = jsonp
request = None
request_id = args.get('id')
if jsonp and self.httprequest.method == 'POST':
# jsonp 2 steps step1 POST: save call
def handler():
self.session['jsonp_request_%s' % (request_id,)] = self.httprequest.form['r']
self.session.modified = True
headers=[('Content-Type', 'text/plain; charset=utf-8')]
r = werkzeug.wrappers.Response(request_id, headers=headers)
return r
self.jsonp_handler = handler
return
elif jsonp and args.get('r'):
# jsonp method GET
request = args.get('r')
elif jsonp and request_id:
# jsonp 2 steps step2 GET: run and return result
request = self.session.pop('jsonp_request_%s' % (request_id,), '{}')
else:
# regular jsonrpc2
request = self.httprequest.get_data().decode(self.httprequest.charset)
# Read POST content or POST Form Data named "request"
try:
self.jsonrequest = json.loads(request)
except ValueError:
msg = 'Invalid JSON data: %r' % (request,)
_logger.info('%s: %s', self.httprequest.path, msg)
raise werkzeug.exceptions.BadRequest(msg)
self.params = dict(self.jsonrequest.get("params", {}))
self.context = self.params.pop('context', dict(self.session.context))
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:44,
示例13: dispatch
点赞 4
# 需要导入模块: import werkzeug [as 别名]
# 或者: from werkzeug import exceptions [as 别名]
def dispatch(self):
if request.httprequest.method == 'OPTIONS' and request.endpoint and request.endpoint.routing.get('cors'):
headers = {
'Access-Control-Max-Age': 60 * 60 * 24,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, X-Debug-Mode'
}
return Response(status=200, headers=headers)
if request.httprequest.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE') \
and request.endpoint.routing.get('csrf', True): # csrf checked by default
token = self.params.pop('csrf_token', None)
if not self.validate_csrf(token):
if token is not None:
_logger.warn("CSRF validation failed on path '%s'",
request.httprequest.path)
else:
_logger.warn("""No CSRF validation token provided for path '%s'
Odoo URLs are CSRF-protected by default (when accessed with unsafe
HTTP methods). See
https://www.odoo.com/documentation/12.0/reference/http.html#csrf for
more details.
* if this endpoint is accessed through Odoo via py-QWeb form, embed a CSRF
token in the form, Tokens are available via `request.csrf_token()`
can be provided through a hidden input and must be POST-ed named
`csrf_token` e.g. in your form add:
* if the form is generated or posted in javascript, the token value is
available as `csrf_token` on `web.core` and as the `csrf_token`
value in the default js-qweb execution context
* if the form is accessed by an external third party (e.g. REST API
endpoint, payment gateway callback) you will need to disable CSRF
protection (and implement your own protection if necessary) by
passing the `csrf=False` parameter to the `route` decorator.
""", request.httprequest.path)
raise werkzeug.exceptions.BadRequest('Session expired (invalid CSRF token)')
r = self._call_function(**self.params)
if not r:
r = Response(status=204) # no content
return r
开发者ID:ocubexo,项目名称:odoo-dingtalk-connector,代码行数:48,
注:本文中的werkzeug.exceptions方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。