[英]How to get modification date of a template file with local timezone in python flask
[英]How to get contents from a local text file to print on individual lines in a html template (Python/Flask)
输出的截图 ,我希望得到来自用户的帖子张贴在各个行。 目前,我输入一个名称,电子邮件和注释,将其传递到app.py文件并将其存储到文本文件。 我返回姓名,电子邮件,评论和评论时间。 当我阅读文件并将其传递回html模板时,帖子会一个接一个地显示(请参阅随附的屏幕截图),而我试图让它们在彼此之间显示一个。 f.write(“ \\ n”)导致实际的文本文件跳过一行,但是这在模板中不会发生。
form_action.html
<html>
<div align = "center">
<body style="background-color: #3DC247;">
<head>
<title>Conor McGregor</title>
</head>
<body>
<div align = "center">
<h1 style="font-family:verdana;">I AM EL CHAPO</h1>
<div align = "center">
<h2 style="font-family:verdana;">YOU'LL DO NUTIN.</h2>
<div align = "center">
<h2 style="font-family:verdana;">Disscusion Page</h2>
<body>
<div id="container">
<div class="title">
<h3 style="font-family:verdana;">Please fill in your details
below and your comment to join the discussion</h3>
</div>
<div id="content">
<form method="post" action="{{ url_for('hello') }}">
<label for="yourname" style="font-family:verdana;">Please
enter your name:</label>
<input type="text" name="yourname" /><br /><br>
<label for="youremail" style="font-family:verdana;">Please
enter your email:</label>
<input type="text" name="youremail" /><br /><br>
<label for="yourcomment"style="font-family:verdana;">Please
enter your comment:</label>
<input type="textarea" name="yourcomment" rows="4" cols="50">
<input type="submit" /><br>
</form>
</div>
</div>
</div>
</div>
<div id="container">
<div class="title">
<h1 style="font-family:verdana;"><p>Comments</p></h1>
</div>
<div id="content">
{{details}}
</div>
</div>
</body>
</html>
app.py
from flask import Flask, render_template, request, url_for
import time
import datetime
# Initialize the Flask application
app = Flask(__name__)
# Define a route for the default URL, which loads the form
@app.route('/')
def form():
return render_template('form_submit.html')
@app.route('/hello/', methods=['POST','GET'])
def hello():
global time
name=request.form['yourname']
email=request.form['youremail']
comment=request.form['yourcomment']
comment_time=time.strftime("%a-%d-%m-%Y %H:%M:%S")
f = open ("user+comments.txt","a")
f.write(name + ' ' + email + ' ' + comment + " " + comment_time)
f.write('\n')
f.close()
with open("user+comments.txt", "r") as f:
details = f.read()
f.close()
return render_template('form_action.html', details = details, name=name,
email=email, comment=comment, comment_time=comment_time)
if __name__ == '__main__':
app.run(debug=True)
HTML不知道\\n
是什么。 您可以通过两种方式解决此问题。
将str
详细信息转换为list
详细信息
details = f.read().split('\\n')
这会将str
对象转换为list
对象。 您可以使用以下命令将其打印在模板中
{% for detail in details %} {{detail}} {% endfor %}
将\\n
替换为<br>
details = f.read().replace('\\n','<br>')
然后在form_action.html
其打印为{{ details|safe }}
。 使用安全过滤器很重要。 <br>
如果没有它,将被转义并呈现为简单文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.