當前位置: 首頁>>代碼示例>>Python>>正文


Python werkzeug.exceptions方法代碼示例

本文整理匯總了Python中werkzeug.exceptions方法的典型用法代碼示例。如果您正苦於以下問題:Python werkzeug.exceptions方法的具體用法?Python werkzeug.exceptions怎麽用?Python werkzeug.exceptions使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在werkzeug的用法示例。


在下文中一共展示了werkzeug.exceptions方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: abort

# 需要導入模塊: 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,代碼來源:exceptions.py

示例2: abort

# 需要導入模塊: 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,代碼來源:exceptions.py

示例3: dispatch

# 需要導入模塊: 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,代碼來源:http.py

示例4: serialize_exception

# 需要導入模塊: 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,代碼來源:http.py

示例5: _handle_exception

# 需要導入模塊: 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,代碼來源:http.py

示例6: not_found

# 需要導入模塊: 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,代碼來源:http.py

示例7: replace_request_password

# 需要導入模塊: 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,代碼來源:http.py

示例8: _call_function

# 需要導入模塊: 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,代碼來源:http.py

示例9: not_found

# 需要導入模塊: import werkzeug [as 別名]
# 或者: from werkzeug import exceptions [as 別名]
def not_found(self, description=None):
        """ Shortcut for a `HTTP 404
        <http://tools.ietf.org/html/rfc7231#section-6.5.4>`_ (Not Found)
        response
        """
        return werkzeug.exceptions.NotFound(description)

#----------------------------------------------------------
# Controller and route registration
#---------------------------------------------------------- 
開發者ID:ocubexo,項目名稱:odoo-dingtalk-connector,代碼行數:12,代碼來源:http.py

示例10: init_app

# 需要導入模塊: 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,代碼來源:api.py

示例11: dispatch_rpc

# 需要導入模塊: 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,代碼來源:http.py

示例12: __init__

# 需要導入模塊: 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,代碼來源:http.py

示例13: dispatch

# 需要導入模塊: 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:

      <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>

* 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,代碼來源:http.py


注:本文中的werkzeug.exceptions方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。