Пользовательская страница ошибки 404 с Python tornado

#python #tornado #traceback

#python #tornado #обратная трассировка

Вопрос:

Я пытаюсь реализовать пользовательскую страницу 404 с помощью python tornado. В документах говорится: « default_handler_class и default_handler_args : Этот обработчик будет использоваться, если не найдено другого соответствия; используйте это для реализации пользовательских страниц 404 (новых в Tornado 3.2).». Нет хорошей информации о том, как должен работать обработчик. Я пытался использовать этот код:

     class defaultHandler(tornado.web.RequestHandler):
        def __init__(self, arg2, arg3):
            print("Called default handler")
            self.arg2 = arg2
            self.arg3 = arg3
    
        def get(self):
            self.write("404 - my thing")
  

Используя эту конфигурацию tornado:

  return tornado.web.Application([
        (r"/main", MainHandler),
        (r"/update_kurse", updateCallback),
        (r"/", LoginPage),
    ], static_path=os.path.join(os.path.dirname(__file__), "static"),
    template_path=os.path.join(os.path.dirname(__file__), "templates"),
    default_handler_class=defaultHandler)
  

Это приводит к ошибке:

 ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadohttp1connection.py", line 273, in _read_message
    delegate.finish()
  File "C:Users******libsite-packagestornadorouting.py", line 268, in finish
    self.delegate.finish()
  File "C:Users******libsite-packagestornadoweb.py", line 2297, in finish
    self.execute()
  File "C:Users******libsite-packagestornadoweb.py", line 2337, in execute
    return self.handler._prepared_future
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
ERROR:tornado.application:Error in exception logger
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1752, in _handle_request_exception
    self.log_exception(*sys.exc_info())
  File "C:Users******libsite-packagestornadoweb.py", line 1790, in log_exception
    self._request_summary(),
  File "C:Users******libsite-packagestornadoweb.py", line 1740, in _request_summary
    self.request.method,
AttributeError: 'function' object has no attribute 'method'
ERROR:tornado.application:Exception in exception handler
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1708, in _execute
    self._handle_request_exception(e)
  File "C:Users******libsite-packagestornadoweb.py", line 1757, in _handle_request_exception
    if self._finished:
AttributeError: 'defaultHandler' object has no attribute '_finished'
ERROR:asyncio:Exception in callback _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333
handle: <Handle _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333>
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libasyncioevents.py", line 145, in _run
    self._callback(*self._args)
  File "C:Users******libsite-packagestornadoweb.py", line 2333, in <lambda>
    fut.add_done_callback(lambda f: f.result())
  File "C:Users******libsite-packagestornadoweb.py", line 1714, in _execute
    if self._prepared_future is not None and not self._prepared_future.done():
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
Called default handler
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadohttp1connection.py", line 273, in _read_message
    delegate.finish()
  File "C:Users******libsite-packagestornadorouting.py", line 268, in finish
    self.delegate.finish()
  File "C:Users******libsite-packagestornadoweb.py", line 2297, in finish
    self.execute()
  File "C:Users******libsite-packagestornadoweb.py", line 2337, in execute
    return self.handler._prepared_future
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
ERROR:tornado.application:Error in exception logger
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1752, in _handle_request_exception
    self.log_exception(*sys.exc_info())
  File "C:Users******libsite-packagestornadoweb.py", line 1790, in log_exception
    self._request_summary(),
  File "C:Users******libsite-packagestornadoweb.py", line 1740, in _request_summary
    self.request.method,
AttributeError: 'function' object has no attribute 'method'
ERROR:tornado.application:Exception in exception handler
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1708, in _execute
    self._handle_request_exception(e)
  File "C:Users******libsite-packagestornadoweb.py", line 1757, in _handle_request_exception
    if self._finished:
AttributeError: 'defaultHandler' object has no attribute '_finished'
ERROR:asyncio:Exception in callback _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333
handle: <Handle _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333>
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libasyncioevents.py", line 145, in _run
    self._callback(*self._args)
  File "C:Users******libsite-packagestornadoweb.py", line 2333, in <lambda>
    fut.add_done_callback(lambda f: f.result())
  File "C:Users******libsite-packagestornadoweb.py", line 1714, in _execute
    if self._prepared_future is not None and not self._prepared_future.done():
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
Called default handler
ERROR:tornado.application:Uncaught exception
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadohttp1connection.py", line 273, in _read_message
    delegate.finish()
  File "C:Users******libsite-packagestornadorouting.py", line 268, in finish
    self.delegate.finish()
  File "C:Users******libsite-packagestornadoweb.py", line 2297, in finish
    self.execute()
  File "C:Users******libsite-packagestornadoweb.py", line 2337, in execute
    return self.handler._prepared_future
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
ERROR:tornado.application:Error in exception logger
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1752, in _handle_request_exception
    self.log_exception(*sys.exc_info())
  File "C:Users******libsite-packagestornadoweb.py", line 1790, in log_exception
    self._request_summary(),
  File "C:Users******libsite-packagestornadoweb.py", line 1740, in _request_summary
    self.request.method,
AttributeError: 'function' object has no attribute 'method'
ERROR:tornado.application:Exception in exception handler
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1708, in _execute
    self._handle_request_exception(e)
  File "C:Users******libsite-packagestornadoweb.py", line 1757, in _handle_request_exception
    if self._finished:
AttributeError: 'defaultHandler' object has no attribute '_finished'
ERROR:asyncio:Exception in callback _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333
handle: <Handle _HandlerDelegate.execute.<locals>.<lambda>(<Task finishe...ed_future'",)>) at C:Users******libsite-packagestornadoweb.py:2333>
Traceback (most recent call last):
  File "C:Users******libsite-packagestornadoweb.py", line 1665, in _execute
    if self.request.method not in self.SUPPORTED_METHODS:
AttributeError: 'function' object has no attribute 'method'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users******libasyncioevents.py", line 145, in _run
    self._callback(*self._args)
  File "C:Users******libsite-packagestornadoweb.py", line 2333, in <lambda>
    fut.add_done_callback(lambda f: f.result())
  File "C:Users******libsite-packagestornadoweb.py", line 1714, in _execute
    if self._prepared_future is not None and not self._prepared_future.done():
AttributeError: 'defaultHandler' object has no attribute '_prepared_future'
  

Что я делаю не так? Я не могу найти ни одного примера рабочей страницы 404 с python tornado. Я изучил маршрутизаторы, но это, похоже, здесь не подходит.

Ответ №1:

Вы никогда не должны переопределять __init__ без вызова __init__ метода суперкласса. RequestHandler.__init__ принимает два аргумента, которые вы должны передать вместе. По этой причине принято переопределять RequestHandler.initialize метод вместо __init__ . Но неясно, что такое arg2 и arg3 в этом примере, поэтому я не уверен, почему вы вообще переопределяете этот метод.

Обычный обработчик 404 будет выглядеть следующим образом:

 class DefaultHandler(RequestHandler):
    def prepare(self):
        # Use prepare() to handle all the HTTP methods
        self.set_status(404)
        self.finish("404 - my thing")
  

Комментарии:

1. Спасибо! Это сработало, я изменил _ _ init _ _, потому что я пробовал разные вещи. (Извините за странный интервал из-за разметки