超过了 Django 最大递归深度。无限查看循环

Posted

技术标签:

【中文标题】超过了 Django 最大递归深度。无限查看循环【英文标题】:Django Maximum Recursion Depth Exceeded. View loops infinitely 【发布时间】:2021-07-24 01:20:15 【问题描述】:

我正在编写一个应用程序,该应用程序将对提供的汽车 VIN 号码的品牌、型号和年份信息进行解码。该脚本独立运行,但是当集成到我的 django 应用程序并通过单击我的 Web 应用程序的按钮调用时,视图开始无限循环并引发 RecursionError。我会在下面提供相关代码

基本 html 模板

<!DOCTYPE html>
%load static%

<Html>
  <title>What the F*cking F*ck</title>
  <head>
  
  </head>

  
  <h1>Here I will attempt to recreate the Working Title File in a somewhat nice looking format. </h1>
  <h4>We'll see what happens</h4>
  
  <div>
    % block header %
    <p>Upload an IPDF with the Browse Button below</p>
    <form method="post" enctype="multipart/form-data">
      % csrf_token %
       form.as_p 
      <button type="submit">Upload</button>
    </form>
    % endblock %
    <p><a href="% url 'wtf' %">Return to upload</a></p>
    <p>

  </div>

  <div id="address">
    % block address %
      <p>This is where stuff would render if you had uploaded something. But you didn't. Or it broke. So shame on both of us.</p>
    % endblock %
  </div>
</Html>

address_render.html(从 base 继承,也称为 wtf)。这个按预期工作。当我单击此处的按钮调用视图 vin_decode 时,它会中断。

% extends "wtf2/wtf.html" %
<script scr='../../jquery-3.6.0.js'>
</script>
% block header %
    <p>Successful Address Validation</p>
    <form action="% url 'vin' %" method='post'>
    % csrf_token %
    <button type="submit">Click here to begin VIN Decode</button>
    </form>
% endblock %

% block address %
<div>
    <p>Sick! The address validation portion worked. Now what? Please Check the returned address. This one came back invalid</p>
    <table>
        <thead>
            <tr>
                <th>Street Lines</th>
                <th>City</th>
                <th>State</th>
                <th>ZIP</th>
                <th>Returned StreetLines</th>
                <th>Returned City</th>
                <th>Returned State</th>
                <th>Returned ZIP</th>
                <th>Returned Status</th>
                <th>Resolved</th>
                <th>Delivery Point Valid</th>
                <th>Interpolated Street Address</th>
                <th>City Match?</th>
                <th>ZIP Match?</th>
                <th>Resolved Address?</th>
                <th>Valid?</th>
            </tr>
        </thead>
        <tbody>
        % if d %
        % for i in d%
        
            <tr>
            % if i.Valid == "No"%
                <td> i.StreetLines </td>
                <td> i.City </td>
                <td> i.State </td>
                <td> i.ZIP </td>
                <td> i.Returned_StreetLines </td>
                <td> i.Returned_City </td>
                <td> i.Returned_State </td>
                <td> i.Returned_ZIP </td>
                <td> i.Returned_Status </td>
                <td> i.Resolved </td>
                <td> i.DPV </td>
                <td> i.InterpolatedStreetAddress </td>
                <td> i.City_Match </td>
                <td> i.ZIP_Match </td>
                <td> i.Resolved_Address </td>
                <td> i.Valid </td>
            % endif %
            </tr>
        % endfor %
        % endif %
        </tbody>
    </table>
</div>
% endblock %

vin_decode.html(也继承自 base.html)

% extends "wtf2/wtf.html" %
% comment % <script scr='../../jquery-3.6.0.js'>
</script> % endcomment %
% block header %
    <p>Successful VIN Decoding</p>
    <p><a href="% url 'wtf' %">Click here to return to upload</a></p>

    
% endblock %

% block address %
<div>
    <p>Sick! The VIN Decoding worked!</p>
    <table>
        <thead>
            <tr>
                <th>Site</th>
                <th>Vehicle Number</th>
                <th>VIN</th>
                <th>Current Device</th>
                <th>Make</th>
                <th>Model</th>
                <th>Year</th>
                <th>Old Make</th>
                <th>Old Model</th>
                <th>Old Year</th>
            </tr>
        </thead>
        <tbody>
        % if d %
        % for i in d%
        
            <tr>
                <td> i.site </td>
                <td> i.vehicle_number </td>
                <td> i.vin </td>
                <td> i.current_device </td>
                <td> i.Returned_Make </td>
                <td> i.Returned_Model </td>
                <td> i.Returned_Year </td>
                <td> i.make </td>
                <td> i.model </td>
                <td> i.year </td>
            </tr>
        % endfor %
        % endif %
        </tbody>
    </table>
</div>
% endblock %

views.py

from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from suds.plugin import Context
from .models import Document
from .forms import DocumentForm
import pandas as pd
import sqlite3
import json
from .Scripts.address_validation import address_validation
from .Scripts.vin_decode import vin_decode
from .Scripts.data_collect import *

# cnxn_string = sqlite3.connect('db.sqlite3')

# Create your views here.
def doc_upload(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            doc = Document.objects.latest('id')
            
            # project_upload(doc.document.path, doc.pk)
            # vehicle_upload(doc.document.path, doc.pk)
            data_collection(doc.document.path,doc.pk)
            df = address_validation(doc.pk)
            json_records = df.reset_index().to_json(orient='records')
            data = json.loads(json_records)
            context = 'd': data
            return render(request, 'wtf2/address_render.html', context)
    else:
        form = DocumentForm()
    return render(request, 'wtf2/wtf.html', 
        'form': form
    )

def vin_decode(request):
    print('Is this thing on')
    doc = Document.objects.latest('id')
    df = vin_decode(doc.pk)
    json_records = df.reset_index().to_json(orient='records')
    df = json.loads(json_records)
    context = 'd': df
    return render(request, 'wtf2/vin_decode.html', context)

urls.py

from django.contrib import admin
from django.urls import path
from introduction import views
from wtf2 import views as wtviews
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('team', views.team, name='team'),
    path('team', views.showdetails, name='PPTracker'),
    path('wtf', wtviews.doc_upload, name='wtf'),
    path('wtf/vin_decode', wtviews.vin_decode, name='vin')
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

知道这里发生了什么吗?我得到一个 RecursionError 重复调用视图的第一行“vin_decode”。我添加了一个调试

print('Is this thing on')

在 vin_decode 视图中进行测试,终端上的错误代码在中断前会打印 1000 次“Is this thing on”。还将添加完整的错误消息。

Is this thing on
Internal Server Error: /wtf/vin_decode
Traceback (most recent call last):
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\ross.martin\Documents\GitHub\Django-Unchained\website-Project\wtf2\views.py", line 40, in vin_decode
    df = vin_decode(doc.pk)
  File "C:\Users\ross.martin\Documents\GitHub\Django-Unchained\website-Project\wtf2\views.py", line 40, in vin_decode
    df = vin_decode(doc.pk)
  File "C:\Users\ross.martin\Documents\GitHub\Django-Unchained\website-Project\wtf2\views.py", line 40, in vin_decode
    df = vin_decode(doc.pk)
  [Previous line repeated 938 more times]
  File "C:\Users\ross.martin\Documents\GitHub\Django-Unchained\website-Project\wtf2\views.py", line 39, in vin_decode
    doc = Document.objects.latest('id')
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 674, in latest
    return self.reverse()._earliest(*fields)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 668, in _earliest
    return obj.get()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 425, in get
    num = len(clone)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 269, in __len__
    self._fetch_all()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 53, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1143, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 498, in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 56, in pre_sql_setup
    order_by = self.get_order_by()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 361, in get_order_by
    resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 249, in resolve_expression
    c.set_source_expressions([
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 250, in <listcomp>
    expr.resolve_expression(query, allow_joins, reuse, summarize)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 247, in resolve_expression
    c = self.copy()
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\expressions.py", line 348, in copy
    return copy.copy(self)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\copy.py", line 102, in copy
    return _reconstruct(x, None, *rv)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\copy.py", line 264, in _reconstruct
    y = func(*args)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\copyreg.py", line 95, in __newobj__
    return cls.__new__(cls, *args)
  File "C:\Users\ross.martin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\deconstruct.py", line 16, in __new__
    obj = super(klass, cls).__new__(cls)
RecursionError: maximum recursion depth exceeded while calling a Python object

【问题讨论】:

from .Scripts.vin_decode import vin_decodedef vin_decode(request): 您导入的函数和您的视图具有相同的名称您只是递归调用您的视图。 df = vin_decode(doc.pk)vin_decode() 函数内?也许这就是问题所在? 【参考方案1】:

您使用以下方法进行递归调用:

def vin_decode(request):
    print('Is this thing on')
    doc = Document.objects.latest('id')
    df = vin_decode(doc.pk)
    json_records = df.reset_index().to_json(orient='records')
    df = json.loads(json_records)
    context = 'd': df
    return render(request, 'wtf2/vin_decode.html', context)

导入vin_decode 无关紧要,因为您通过定义同名函数来覆盖它。

您可以将模块的vin_decode 导入为另一个名称,然后调用该函数,因此:

from .Scripts.vin_decode import vin_decode as vin_decode_func

# …

def vin_decode(request):
    print('Is this thing on')
    doc = Document.objects.latest('id')
    df = vin_decode_func(doc.pk)
    json_records = df.reset_index().to_json(orient='records')
    df = json.loads(json_records)
    context = 'd': df
    return render(request, 'wtf2/vin_decode.html', context)

【讨论】:

哇,非常感谢您为我指出这一点。我将视图的名称更改为 vin_view 并解决了所有问题。有时只是采取第 3 方的观点来指出显而易见的事情。非常感谢威廉【参考方案2】:

您将 vin_decode 名称用于两件事:您导入的一个函数

from .Scripts.vin_decode import vin_decode

然后是视图本身。

df = vin_decode(doc.pk) 中,您认为您正在调用函数,但视图正在无限循环中调用自身。

最简单的解决方案:用另一个名称命名您的视图,例如 vin_decode_view

【讨论】:

感谢您为我指出这一点。我将视图重命名为 vin_view 并解决了所有问题。非常感谢 我很高兴它有帮助。您能否将我的答案标记为已接受?谢谢!

以上是关于超过了 Django 最大递归深度。无限查看循环的主要内容,如果未能解决你的问题,请参考以下文章

超过最大更新深度。使用 TimePickerInput onChange 事件 React.js 时的无限循环

python递归函数及二分法查找

超过最大更新深度 - React Js

ReactJs 超过最大更新深度

ReactNative:超过最大更新深度错误

比较超过最大递归深度?