RecursionError: maximum recursion depth exceeded error in flask app

RecursionError: maximum recursion depth exceeded error in flask app


我在我的应用程序上遇到了递归错误。该应用程序基本上是一个基于 python + flask 的投资组合生成器。页面是使用表单输入和 jinja 生成的。这是我的第一个大项目,我是初学者,我真的找不到这里有什么问题。我认为问题可能出在表单上,​​错误发生在我重新加载生成的页面或返回表单后,并且一直持续到我重新启动PyCharm(不仅是项目本身)。

main.py

from flask import Flask, \
    render_template, \
    redirect, \
    url_for, \
    request, \
    session \

import requests
import os
from flask_session.__init__ import Session

UPLOAD_FOLDER = 'static/uploaded_images'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

app = Flask(__name__)
app.debug = True
app.config['IMAGE_UPLOADS'] = UPLOAD_FOLDER
app.config["SESSION_TYPE"] = "filesystem"
Session(app)



@app.route('/')
def index():
    return redirect('/main')


@app.route('/main')
def main():
    return render_template('index.html')


@app.route('/form')
def form():
    return render_template('form.html')


@app.route('/mainPage', methods=['POST'])
def mainPage():
    if request.method == 'POST':
        session['portfolioName'] = request.form['portfolioName']

        if request.form['colors'] == 'light':
            session['backgroundColor'] = '#FFFFFF'
            session['fontColor'] = '#606367'
        elif request.form['colors'] == 'dark':
            session['backgroundColor'] = '#757575'
            session['fontColor'] = '#E8D4D4'
        else:
            session['backgroundColor'] = request.form['background']
            session['fontColor'] = request.form['font']

        gridLayout = request.form['grid']
        gridLayout = gridLayout.split("x", 1)
        columns = int(gridLayout[0])

        session['language'] = request.form['language']

        session['menuElementsQty'] = int(request.form['menuElements'])
        session['menuItems'] = []
        session['siteContent'] = []

        if session['menuElementsQty'] == 4:
            session['menuItems'].append(request.form['menuItem1'])
            session['menuItems'].append(request.form['menuItem2'])
            session['menuItems'].append(request.form['menuItem3'])
            session['menuItems'].append(request.form['menuItem4'])

            session['siteContent'].append(request.form['description2'])
            session['siteContent'].append(request.form['description3'])
            session['siteContent'].append(request.form['description4'])

        elif session['menuElementsQty'] == 3:
            session['menuItems'].append(request.form['menuItem1'])
            session['menuItems'].append(request.form['menuItem2'])
            session['menuItems'].append(request.form['menuItem3'])

            session['siteContent'].append(request.form['description2'])
            session['siteContent'].append(request.form['description3'])

        elif session['menuElementsQty'] == 2:
            session['menuItems'].append(request.form['menuItem1'])
            session['menuItems'].append(request.form['menuItem2'])

            session['siteContent'].append(request.form['description2'])

        elif session['menuElementsQty'] == 1:
            session['menuItems'].append(request.form['menuItem1'])

        filenames=[]
        session['images'] = request.files.getlist('image')
        for image in session['images']:
            image.save(os.path.join(app.config['IMAGE_UPLOADS'], image.filename))
            filenames.append(image.filename)

        imageQty = len(session['images'])

        # url = 'some URL to post later'
        # html_output_name = 'test.htm'
        # req = requests.get(url, 'html.parser')
        #
        # with open(html_output_name, 'w') as f:
        #     f.write(req.text)
        #     f.close()

        session.modified = True
        return render_template('mainPage.html', images=filenames, menuItems=session['menuItems'],menuElementsQty=session['menuElementsQty'], imageQty=imageQty, columns=columns, portfolioName=session['portfolioName'], language=session['language'], backgroundColor=session['backgroundColor'], fontColor=session['fontColor'])
    return render_template('form.html')


@app.route('/secondPage')
def secondPage():
    return render_template('secondPage.html', menuItems=session['menuItems'], menuElementsQty=session['menuElementsQty'], backgroundColor=session['backgroundColor'], fontColor=session['fontColor'], language=session['language'], siteContent=session['siteContent'])

@app.route('/thirdPage')
def thirdPage():
    return render_template('thirdPage.html', menuItems=session['menuItems'], menuElementsQty=session['menuElementsQty'], backgroundColor=session['backgroundColor'], fontColor=session['fontColor'], language=session['language'], siteContent=session['siteContent'])

@app.route('/fourthPage')
def fourthPage():
    return render_template('fourthPage.html', menuItems=session['menuItems'], menuElementsQty=session['menuElementsQty'], backgroundColor=session['backgroundColor'], fontColor=session['fontColor'], language=session['language'], siteContent=session['siteContent'])


if __name__ == "__main__":
    app.run(host='0.0.0.0', port='5000', debug=True)

form.html

<form action="{{ url_for('mainPage') }}" method="post" enctype="multipart/form-data">

                        <!--Name-->
                        <div class="row">
                            <details>
                                <summary>Podaj nazwę swojej strony.</summary>
                                <h5>To może być Twoje imię i nazwisko, pseudonim artystyczny, cokolwiek, co będzie Twoim znakiem rozpoznawczym.</h5>
                            </details>
                                <div class="col">
                                    <input type="text" name="portfolioName"/>
                                </div>
                        </div>

                        <!--Colors-->
                        <div class="row radioHidden">
                            <details>
                                <summary>Wybierz motyw kolorystyczny.</summary>
                                <h5>Możesz wybrać zarówno jeden z naszych gotowych motywów lub wybrać własne kolory.</h5>
                            </details>
                            <div class="col-md-5">
                                <label>
                                    <input type="radio" name="colors" id="light" value="light" checked/>
                                    <img class='img-fluid' src="static/img/light.png">
                                </label>
                            </div>
                            <div class="col-md-5">
                                <label>
                                    <input type="radio" name="colors" id="dark" value="dark"/>
                                    <img class='img-fluid' src="static/img/dark.png" >
                                </label>
                            </div>
                            <div class="col-md-2">
                                <label>
                                    <input type="radio" name="colors" id="custom" value="custom"/>
                                    Własne
                                </label>
                                <div class="Box" style="display:none">
                                    <div class="row">
                                        <label>Kolor tła</label>
                                        <input type="color" name="background" id="background" value="#865555">
                                    </div>
                                    <div class="row">
                                        <label>Kolor tekstu</label>
                                        <input type="color" name="font" id="font" value="#ECE2E2">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--Grid style-->
                        <div class="row radioHidden">
                            <details>
                                <summary>Wybierz układ.</summary>
                                <h5>Obrazy będą wyświetlane w siatce (tzw. grid) w jednym z wybranych układów.</h5>
                            </details>
                            <div class="col-md">
                                <label>
                                    <input type="radio" name="grid" id="3x2" value="3x2"/>
                                    <img class='img-fluid' src="static/img/grid3x2.png">
                                </label>
                            </div>
                            <div class="col-md">
                                <label>
                                    <input type="radio" name="grid" id="3x3" value="3x3"/>
                                    <img class='img-fluid' src="static/img/grid3x3.png">
                                </label>
                            </div>
                            <div class="col-md">
                                <label>
                                    <input type="radio" name="grid" id="4x3" value="4x3"/>
                                    <img class='img-fluid' src="static/img/grid4x3.png">
                                </label>
                            </div>

                        </div>

                        <!--Language-->
                        <div class="row radioHidden">
                            <details>
                                <summary>Wybierz wersję językową.</summary>
                                <h5>Cała strona będzie dostępna w jednym z dwóch języków. Pamiętaj jednak, że treści, które wpisujesz, będą w takim języku, w jakim je napiszesz!</h5>
                            </details>
                            <div class="col-md">
                                <label>
                                    <input type="radio" name="language" id="pl" value="pl"/>
                                    <i class="flag flag-poland"></i>
                                </label>
                                <label>
                                    <input type="radio" name="language" id="en" value="en"/>
                                    <i class="flag flag-united-states"></i>
                                </label>
                            </div>
                        </div>

                        <!--Menu elements-->
                        <div class="row">
                            <details>
                                <summary>Wybierz elementy menu</summary>
                                <h5>Maksymalnie możesz wybrać 4 elementy menu, czyli cztery podstrony, których treść będziesz uzupełniać w dalszych krokach.
                                    Dlaczego akurat cztery? Im bardziej minimalistyczna strona, tym przejrzyściej wygląda i lepiej się prezentuje!
                                    Spróbuj zmieścić swoje treści w tych czterech podstronach.</h5>
                            </details>
                            <div class="row">
                                <div class="row">
                                    <div class="col-md">
                                        Z ilu elementów ma się składać menu?
                                        1<input type="radio" name="menuElements" id="1" value="1" checked="checked"/>
                                        2<input type="radio" name="menuElements" id="2" value="2"/>
                                        3<input type="radio" name="menuElements" id="3" value="3"/>
                                        4<input type="radio" name="menuElements" id="4" value="4"/>
                                    </div>
                                </div>
                                <div class="row firstPage"  style="display:none">
                                    <div class="col-md-3">
                                        Pierwsza podstrona
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" name="menuItem1" id="menuItem1" value="Galeria"/>
                                    </div>
                                    <div class="col-md-6">
                                        <p>Tu nie wpisujesz swojej treści. Na tej podstronie wyświetlać się będą Twoje prace.</p>
                                    </div>
                                </div>
                                <div class="row secondPage"  style="display:none">
                                    <div class="col-md-3">
                                        Druga podstrona
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" name="menuItem2" id="menuItem2" value="O mnie"/>
                                    </div>
                                    <div class="col-md-6">
                                        <textarea name="description2" id="menuItem2desc" class="bigInput">
                                            <h1>Lorem ipsum dolor sit amet</h1>
                                            <p>consectetur adipiscing elit. Maecenas iaculis tempus finibus. Nullam vehicula egestas leo, dictum ultrices odio sagittis in. Sed ornare nunc nec nulla feugiat, a eleifend magna bibendum. Nam vel lectus vel mi commodo tincidunt. Donec sit amet ullamcorper risus, nec rhoncus nibh. Praesent in lectus ultrices, pellentesque nunc vel, fermentum ipsum. Integer a aliquet erat. Curabitur porta feugiat purus, ac venenatis neque consequat vitae. Praesent pellentesque ex erat, sit amet dictum lacus rhoncus quis. Integer non lobortis lorem, eu finibus ligula. Nulla varius dolor vitae dapibus facilisis. Nam et nulla ut lectus vestibulum commodo eu et diam. Proin id sem turpis. In a enim libero. Integer placerat enim ex, quis lobortis nibh feugiat quis. Nam placerat mollis urna, in aliquam nisi varius id.

                                            <strong>Nulla vitae felis est.</strong> Sed scelerisque, metus non sollicitudin commodo, diam metus hendrerit mauris, quis faucibus turpis neque quis leo. Praesent dapibus magna est, non pharetra diam finibus et. Aenean laoreet ac elit suscipit dictum. Duis in porttitor odio, ut porttitor est. Vestibulum eget auctor enim, non fringilla est. Proin pretium turpis lorem, non blandit felis accumsan nec. Aenean pellentesque risus sit amet massa scelerisque, vitae porttitor nisi placerat.</p>

                                            Nullam ut nisl faucibus, lacinia neque eget, ultricies massa. Proin quis velit at orci blandit vestibulum ut ut libero. Nulla facilisi. Nullam facilisis, ligula id porttitor gravida, nulla velit finibus nunc, finibus sodales tellus risus non risus. Pellentesque lacinia lacinia justo in faucibus. Duis et leo id elit tincidunt molestie ut id ex. Nunc laoreet nisl non mattis interdum. Maecenas id auctor dolor. Donec consequat tellus ornare, vulputate tellus id, pellentesque augue. Donec congue at quam eu elementum. Quisque dapibus mattis enim.

                                            Maecenas ac faucibus neque. Pellentesque a viverra magna. Proin lectus tortor, tempus id consectetur quis, condimentum eget tellus. In ultricies varius nisl ut imperdiet. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Vivamus ac mi neque. Cras finibus tortor quis elit eleifend placerat. Cras at enim dui. Vestibulum libero massa, eleifend nec rhoncus lacinia, sodales vel ante. Nulla accumsan nisi in sapien tincidunt lacinia. Praesent elit arcu, lobortis et consectetur vitae, tincidunt quis ligula.

                                            Etiam aliquam nibh a volutpat tincidunt. Donec nec scelerisque metus. Vivamus id sapien iaculis, pretium tellus vel, tempor mauris. Ut sit amet luctus neque. Mauris convallis eget velit a faucibus. Sed vestibulum rutrum facilisis. Cras laoreet eu arcu vitae dignissim.                                        </textarea>
                                    </div>
                                </div>
                                <div class="row thirdPage"  style="display:none">
                                    <div class="col-md-3">
                                        Trzecia podstrona
                                    </div>
                                    <div class="col-md-3">
                                            <input type="text" name="menuItem3" id="menuItem3" value="Kontakt"/>
                                     </div>
                                    <div class="col-md-6">
                                        <textarea name="description3" id="menuItem3desc" class="bigInput">Kontakt
                                        </textarea>
                                    </div>
                                </div>
                                <div class="row fourthPage"  style="display:none">
                                    <div class="col-md-3">
                                        Czwarta podstrona
                                    </div>
                                    <div class="col-md-3">
                                        <input type="text" name="menuItem4" id="menuItem4" value="..."/>
                                     </div>
                                    <div class="col-md-6">
                                        <textarea name="description4" id="menuItem4desc" class="bigInput">...
                                        </textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <details>
                                <summary>Wrzuć swoje obrazy.</summary>
                                <h5>Cała strona będzie dostępna w jednym z dwóch języków. Pamiętaj jednak, że treści, które wpisujesz, będą w takim języku, w jakim je napiszesz!</h5>
                            </details>
                                <input type="file" name="image" accept="image/*" multiple>
                            <button type="submit" class="btn btn-primary btn-block mb-4">Generuj!</button>
                        </div>
                    </form>

generatedPage.html

<!DOCTYPE html>
<html lang="{{ language }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">
    <link rel="stylesheet" href="static/css/mdb.min.css" />
    <title>{{ portfolioName }}</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;700&display=swap');
        {% include 'styles.css' %}
    </style>
</head>
<body>

    <div class="container">
        <div class="row">
            {% include 'headerTemplate.html' %}
            <hr>
        </div>

        {% for image in images: %}
            <div class="row mt-4">
            {% for column in range(columns): %}
                 <div class="col">
                    <div class=" img-overlay-container">
                        <img class='img-fluid' src="{{ url_for('static', filename = 'uploaded_images/' + image) }}" >
                        <div class="overlay" onclick="openModal();currentSlide(1)">
                            <div class="text">Hello World</div>
                        </div>
                    </div>
                </div>
            {% endfor %}
            </div>
        {% endfor %}

        <div class="row">
            <div class="preview">
                <p>This is a preview</p>
                <p>To get the package please press the button</p>
            </div>
        </div>
    </div>

    <div id="myModal" class="modal">
      <span class="close cursor" onclick="closeModal()">&times;</span>
      <div class="modal-content">

        {% for image in images: %}
            <div class="mySlides">
              <img src="{{ url_for('static', filename = '/uploaded_images/' + image) }}" style="max-height=100%">
            </div>
        {% endfor %}
        <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
        <a class="next" onclick="plusSlides(1)">&#10095;</a>

        <div class="caption-container">
          <p id="caption"></p>
        </div>
      </div>
    </div>

<script>
function openModal() {
  document.getElementById("myModal").style.display = "block";
}

function closeModal() {
  document.getElementById("myModal").style.display = "none";
}

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}
</script>
</body>
</html>

错误日志

172.22.240.1 - - [24/Apr/2022 13:47:53] "GET / HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/flask/app.py", line 2463, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/lib/python3/dist-packages/flask/app.py", line 2449, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/lib/python3/dist-packages/flask/app.py", line 1866, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/lib/python3/dist-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/lib/python3/dist-packages/flask/app.py", line 2445, in wsgi_app
    ctx.push()
  File "/usr/lib/python3/dist-packages/flask/ctx.py", line 390, in push
    self.session = session_interface.open_session(self.app, self.request)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/flask_session/sessions.py", line 344, in open_session
    data = self.cache.get(self.key_prefix + sid)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/cachelib/file.py", line 195, in get
    return self.serializer.load(f)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/cachelib/serializers.py", line 29, in load
    data = pickle.load(f)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/werkzeug/datastructures.py", line 3034, in __getattr__
    return getattr(self.stream, name)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/werkzeug/datastructures.py", line 3034, in __getattr__
    return getattr(self.stream, name)
  File "/home/hanuszka/.local/lib/python3.8/site-packages/werkzeug/datastructures.py", line 3034, in __getattr__
    return getattr(self.stream, name)

...
RecursionError: maximum recursion depth exceeded

该堆栈跟踪表明会话中已保存了一些内容,该内容正在抵抗反序列化。我看到在会话中保存代码的唯一不寻常的事情是

session['images'] = request.files.getlist('image')

尽量不要那样做。