【问题标题】:Mpld3 inside of Django Views - "NoneType" Object has no attribute "split"Django 视图中的 Mpld3 - “NoneType”对象没有属性“split”
【发布时间】:2017-10-05 13:39:37
【问题描述】:

我正在尝试使用 AJAX 向我的 Django 后端发出请求。我得到了 AJAX 部分的工作,但我现在正试图返回一个 mpld3 图形以在页面上显示它。

这是 HTML 表单:

               <form id="pointform" method="POST">
                  {% csrf_token %}
                  <div class="row">
                    <div class="col-lg-6 col-md-6">
                      <input name="x_coord" type="text" accept=""id="x_coordinate" class="form-control form-control-md" type="text" placeholder="X-Coordinate">
                    </div>
                    <div class="col-lg-6 col-md-6">
                      <input name="y_coord" type="text" id="y_coordinate" class="form-control form-control-md" type="text" placeholder="Y-Coordinate">
                    </div>
                  </div>
                  <button style="width: 100%" type="submit" class="btn btn-danger">Add Point</button>
              </form>

这是我的 AJAX 请求:

      $.ajax({
          type: "POST",
          url: url,
          data: data,
          dataType: "json",
          success: function(json){

          },            
      });

这是我的观点:

import mpld3
import matplotlib.pyplot as plt

X = []
y = []

def get_figure(request):

    x_coord = request.POST['X']
    y_coord = request.POST['Y']

    X.append(x_coord)
    y.append(y_coord)

    fig = plt.figure()
    plt.scatter(X, y)
    model = mpld3.fig_to_html(fig)

    data = {'Model': model}

    return JsonResponse(data)

这是来自命令行的整个回溯:

File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User\Desktop\mlapp06\regression\views.py", line 24, in get_regression_graph
    fig = plt.figure()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\pyplot.py", line 535, in figure
    **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 81, in new_figure_manager
    return new_figure_manager_given_figure(num, figure)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 98, in new_figure_manager_given_figure
    icon_img = Tk.PhotoImage(file=icon_fname)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3394, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\tkinter\__init__.py", line 3350, in __init__
    self.tk.call(('image', 'create', imgtype, name,) + options)
RuntimeError: main thread is not in main loop
[05/Oct/2017 15:54:51] "POST /ajax/get_regression_graph/ HTTP/1.1" 500 18714
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 332, in send_headers
    self.send_preamble()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 255, in send_preamble
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\socket.py", line 593, in write
    return self._sock.send(b)
ConnectionAbortedError: [WinError 10053] Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen
[05/Oct/2017 15:54:51] "POST /ajax/get_regression_graph/ HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53724)
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 138, in run
    self.finish_response()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 332, in send_headers
    self.send_preamble()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 255, in send_preamble
    ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 453, in _write
    result = self.stdout.write(data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\socket.py", line 593, in write
    return self._sock.send(b)
ConnectionAbortedError: [WinError 10053] Eine bestehende Verbindung wurde softwaregesteuert
durch den Hostcomputer abgebrochen

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 141, in run
    self.handle_error()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\servers\basehttp.py", line 95, in handle_error
    super(ServerHandler, self).handle_error()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 368, in handle_error
    self.finish_response()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 180, in finish_response

    self.write(data)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 274, in write
    self.send_headers()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 331, in send_headers
    if not self.origin_server or self.client_is_modern():
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 344, in client_is_modern
    return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\socketserver.py", line 625, in process_request_thread
    self.finish_request(request, client_address)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\socketserver.py", line 354, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\socketserver.py", line 681, in __init__
    self.handle()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
    handler.run(self.server.get_app())
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\handlers.py", line 144, in run
    self.close()
  File "C:\Users\User\AppData\Local\Programs\Python\Python35\lib\wsgiref\simple_server.py", line 36, in close
    self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'

关于为什么会发生的任何建议?

提前致谢

【问题讨论】:

  • 你能发布完整的堆栈回溯吗?
  • 好的,完成-----
  • 发生这种情况是因为您假设 self.status 设置为 None 以外的其他值,但它是 None
  • 那么,我该如何解决呢?
  • 它是否适用于shell 管理命令? fig = plt.figure() plt.scatter(X, y) model = mpld3.fig_to_html(fig) 如果是,那么请把模型值放在这里?

标签: jquery python django matplotlib mpld3


【解决方案1】:

我猜代码是在没有任何图形输出的服务器上运行的。因此,创建图形可能会失败。您可以使用非 GUI 后端,例如

import matplotlib
matplotlib.use("Agg")
import mpld3
import matplotlib.pyplot as plt
# ... rest of code

【讨论】:

  • 不,不幸的是不是这样。它在我的本地主机上运行。
  • localhost 是一个服务器。运行上述代码或其他代码时,您是否遇到相同的错误? (我猜它是不同的,因此最好知道那个的完整错误回溯)
  • 还是一样。
  • 在这种情况下,您不会显示完整的代码。问题中的错误是由一些Tkinter 问题触发的,如果您使用“Agg”后端,则不会出现该问题。 errortraceback 中还有一些get_regression_graph 不是代码的一部分。您需要确保提供问题的minimal reproducible example
  • 你不明白我的意思吗?如果您使用matplotlib.use("Agg"),则不会收到来自backend_tkagg.py 的错误。这意味着您要么得到一个不同的错误并需要显示它,要么import matplotlib matplotlib.use("Agg") 行不是代码中的第一行,因此它们被忽略了。
【解决方案2】:

你是从另一个线程调用它吗? TKinter 需要在主线程中运行。

请检查这些类似的问题是否有助于解决您的问题: RuntimeError: main thread is not in main loop https://www.reddit.com/r/learnpython/comments/69z9fs/error_main_thread_not_in_main_loop/

【讨论】:

  • 我想更重要的是,在为 Web 输出创建图形时,您实际上根本不想使用 Tkinter。因此,正如我在回答中所建议的那样,更改后端可能是要走的路。
猜你喜欢
  • 2016-09-11
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-13
  • 2019-01-15
  • 2022-11-29
相关资源
最近更新 更多