From 5695bf39a4923953c3b0a7f3242e6926385834d7 Mon Sep 17 00:00:00 2001 From: pelle Jakovits <pelle.jakovitsh@ut.ee> Date: Tue, 11 Mar 2025 09:20:17 +0200 Subject: [PATCH] Example code for exercise 5.1 --- app.py | 12 +++++++++--- templates/home.html | 11 ++++++----- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/app.py b/app.py index 127eb3b..ae2ab5a 100644 --- a/app.py +++ b/app.py @@ -5,17 +5,19 @@ from flask import Flask, render_template, request app = Flask(__name__) +UPLOAD_FOLDER ='./static/images' def read_messages_from_file(): """ Read all messages from a JSON file""" with open('data.json') as messages_file: return json.load(messages_file) -def append_message_to_file(content): +def append_message_to_file(img_path, content): """ Read the contents of JSON file, add this message to it's contents, then write it back to disk. """ data = read_messages_from_file() new_message = { 'content': content, + 'img_path': img_path, 'timestamp': datetime.now().isoformat(" ", "seconds") } @@ -29,10 +31,14 @@ def append_message_to_file(content): # The Flask route, defining the main behaviour of the webserver: @app.route("/handle_message", methods=['POST']) def handleMessage(): + img_path = "" new_message = request.form['msg'] - + if('file' in request.files and request.files['file']): + image = request.files['file'] + img_path = os.path.join(UPLOAD_FOLDER, image.filename) + image.save(img_path) if new_message: - append_message_to_file(new_message) + append_message_to_file(img_path, new_message) return render_template('handle_message.html', message=new_message) diff --git a/templates/home.html b/templates/home.html index 3f16144..fc6505a 100644 --- a/templates/home.html +++ b/templates/home.html @@ -3,22 +3,23 @@ https://jinja.palletsprojects.com/en/3.0.x/ --> <title>Message board</title> <body> - <h4>Welcome to Message board </h4> + <h4>Welcome to Pelle's Message board </h4> There are {{ messages|length }} messages on the board. </ br> <h4> Here are the last 10:</h4> <ul> {% for m in messages[-9:]|reverse %} - <li> - "{{m.content}}" <small>Posted on {{m.timestamp}} </small> - </li> + <li> + "{{m.content}}" <small>Posted on {{m.timestamp}} </small> <img src="{{ m.img_path }}" width="500"> + </li> {% endfor %} </ul> <h4> Enter a new message</h4> - <form action="/handle_message" method="post" > + <form action="/handle_message" method="post" enctype=multipart/form-data > <label >Your message:</label><br> <input type="text" name="msg"><br> + <input type="file" name="file"><br> <input type="submit" value="Submit"> </form> </body> -- GitLab