I'm stuck on the recursion error on my app. The app is basically a portfolio generator based on python flask. Pages are generated using form input and jinja. It's my first big project, I'm a beginner, and I really cannot find what's wrong here. I think the problem might be the form, the error occurs after I reload the generated page or go back to the form and it lasts until I restart PyCharm (not only the project itself).
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 >
<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 >
<input type="text" name="portfolioName"/>
</div>
</div>
<!--Colors-->
<div >
<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 >
<label>
<input type="radio" name="colors" id="light" value="light" checked/>
<img class='img-fluid' src="static/img/light.png">
</label>
</div>
<div >
<label>
<input type="radio" name="colors" id="dark" value="dark"/>
<img class='img-fluid' src="static/img/dark.png" >
</label>
</div>
<div >
<label>
<input type="radio" name="colors" id="custom" value="custom"/>
Własne
</label>
<div style="display:none">
<div >
<label>Kolor tła</label>
<input type="color" name="background" id="background" value="#865555">
</div>
<div >
<label>Kolor tekstu</label>
<input type="color" name="font" id="font" value="#ECE2E2">
</div>
</div>
</div>
</div>
<!--Grid style-->
<div >
<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 >
<label>
<input type="radio" name="grid" id="3x2" value="3x2"/>
<img class='img-fluid' src="static/img/grid3x2.png">
</label>
</div>
<div >
<label>
<input type="radio" name="grid" id="3x3" value="3x3"/>
<img class='img-fluid' src="static/img/grid3x3.png">
</label>
</div>
<div >
<label>
<input type="radio" name="grid" id="4x3" value="4x3"/>
<img class='img-fluid' src="static/img/grid4x3.png">
</label>
</div>
</div>
<!--Language-->
<div >
<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 >
<label>
<input type="radio" name="language" id="pl" value="pl"/>
<i ></i>
</label>
<label>
<input type="radio" name="language" id="en" value="en"/>
<i ></i>
</label>
</div>
</div>
<!--Menu elements-->
<div >
<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 >
<div >
<div >
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 style="display:none">
<div >
Pierwsza podstrona
</div>
<div >
<input type="text" name="menuItem1" id="menuItem1" value="Galeria"/>
</div>
<div >
<p>Tu nie wpisujesz swojej treści. Na tej podstronie wyświetlać się będą Twoje prace.</p>
</div>
</div>
<div style="display:none">
<div >
Druga podstrona
</div>
<div >
<input type="text" name="menuItem2" id="menuItem2" value="O mnie"/>
</div>
<div >
<textarea name="description2" id="menuItem2desc" >
<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 style="display:none">
<div >
Trzecia podstrona
</div>
<div >
<input type="text" name="menuItem3" id="menuItem3" value="Kontakt"/>
</div>
<div >
<textarea name="description3" id="menuItem3desc" >Kontakt
</textarea>
</div>
</div>
<div style="display:none">
<div >
Czwarta podstrona
</div>
<div >
<input type="text" name="menuItem4" id="menuItem4" value="..."/>
</div>
<div >
<textarea name="description4" id="menuItem4desc" >...
</textarea>
</div>
</div>
</div>
</div>
<div >
<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" >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 >
<div >
{% include 'headerTemplate.html' %}
<hr>
</div>
{% for image in images: %}
<div >
{% for column in range(columns): %}
<div >
<div >
<img class='img-fluid' src="{{ url_for('static', filename = 'uploaded_images/' image) }}" >
<div onclick="openModal();currentSlide(1)">
<div >Hello World</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endfor %}
<div >
<div >
<p>This is a preview</p>
<p>To get the package please press the button</p>
</div>
</div>
</div>
<div id="myModal" >
<span onclick="closeModal()">×</span>
<div >
{% for image in images: %}
<div >
<img src="{{ url_for('static', filename = '/uploaded_images/' image) }}" style="max-height=100%">
</div>
{% endfor %}
<a onclick="plusSlides(-1)">❮</a>
<a onclick="plusSlides(1)">❯</a>
<div >
<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>
Error log
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
CodePudding user response:
That stack trace is saying that something has been saved in the session that is resisting being deserialized. The only unusual thing I see that code saving in the session is
session['images'] = request.files.getlist('image')
Try not doing that.