Skip to content
Snippets Groups Projects
Commit 6580e51c authored by shivupoojar's avatar shivupoojar
Browse files

Added for files

parent d121382b
No related branches found
No related tags found
No related merge requests found
app.py 0 → 100644
import json
from datetime import datetime
from flask import Flask, render_template, request
app = Flask(__name__)
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):
""" 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,
'timestamp': datetime.now().isoformat(" ", "seconds")
}
data['messages'].append(new_message)
with open('data.json', mode='w') as messages_file:
json.dump(data, messages_file)
# The Flask route, defining the main behaviour of the webserver:
@app.route("/")
def home():
new_message = request.args.get('msg')
if new_message:
append_message_to_file(new_message)
data = read_messages_from_file()
# Return a Jinja HTML template, passing the messages as an argument to the template:
return render_template('home.html', messages=data['messages'])
{"messages": []}
\ No newline at end of file
# this file defines the pip packages neede by this application
flask==2.0.2
\ No newline at end of file
<!doctype html>
<!-- This is a Jinja based template. To read more about Jinja, check
https://jinja.palletsprojects.com/en/3.0.x/ -->
<title>Message board</title>
<body>
<h4>There are {{ messages|length }} messages on the board.</h4>
<h4> Here are the last 10:</h4>
<ul>
{% for m in messages[-9:]|reverse %}
<li>
"{{m.content}}" <small>Posted on {{m.timestamp}}</small>
</li>
{% endfor %}
</ul>
<h4> Enter a new message</h4>
<form action="/">
<label >Your message:</label><br>
<input type="text" name="msg"><br>
<input type="submit" value="Submit">
</form>
</body>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment