使用tryexcept块覆盖方法

时间:2019-02-21 05:17:14

标签: python-3.x odoo

以下是Odoo中用于处理异常的内置方法:

class HttpRequest(WebRequest):
    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

我需要重写此方法,并在if redirect:内添加更多功能,如下所示:

  if redirect:
      query = werkzeug.urls.url_encode({ 'redirect': redirect, })
      if 'web' in redirect:
           return werkzeug.utils.redirect('/web/login?%s' % query)
      else:
           return werkzeug.utils.redirect('/login?%s' %   query)

我们该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用普通的旧Pythonic继承来实现此目的,例如,在模块模型内部创建一个http_inherit.py文件并像这样进行继承:

from odoo.http import HttpRequest

class InheritHttpRequest(HttpRequest):
  def _handle_exception(self, exception):
    ...
    ...
    if redirect:
      query = werkzeug.urls.url_encode({ 'redirect': redirect, })
      if 'web' in redirect:
        return werkzeug.utils.redirect('/web/login?%s' % query)
      else:
        return werkzeug.utils.redirect('/login?%s' %   query)

请不要忘记将该文件导入模块 init .py。如果需要调用原始的_handle_exception函数,可以调用super;也可以将整个原始函数粘贴到继承的函数中,并添加其他功能。安装此模块时,_handle_exception的功能将取决于您继承的功能。