我得到了我的头围绕python和运行它关闭服务器(在这种情况下瓶)。基本上我试图打印本地文本文件的一些内容到一个HTML页面。我从用户那里获取一些输入值(名称,电子邮件和评论),然后将这些输入值逐行存储到本地文本文件中。目前,我可以在网页上获得最新的输入内容(即评论,用户的姓名和电子邮件),但每次表单重新提交时都会被替换。我现在只是搞乱了它(例如,我从文件读取并打印5个用户输入实例到服务器)。不过,我试图在form_action.html页面上打印名称,电子邮件和注释,并保留所有以前的注释。正如我所说我可以打印内容,并且它们显示在cmd提示符中,但是可以通过Javascript来完成,也许它会显示在html页面上,或者可以使用不同的方式使用python来完成。我正在使用的书不包括如何做到这一点,我也找不到任何网上的东西。任何人都能治好我的好奇心?如果我没有理智,请问我,我会很乐意详细说明。干杯!是否可以通过Javascript或python(Flask)将文本文件中的数据打印到html页面?
app.py
from flask import Flask, render_template, request, url_for
# 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')
# Define a route for the action of the form, for example '/hello/'
# We are also defining which type of requests this route is
# accepting: POST requests in this case
@app.route('/hello/', methods=['POST'])
def hello():
name=request.form['yourname']
email=request.form['youremail']
comment=request.form['yourcomment']
f = open ("user+comments.txt","a")
f.write(name)
f.write(' ')
f.write(email)
f.write(' ')
f.write(comment)
f.write('\n')
f.close()
#This reads the the first 5 lines and prints them to the cmd prompt
with open("user+comments.txt") as f:
i = 1
for x in range (0,5):
lines = f.readlines(i)
print(lines)
i+=1
x+=1
f.close()
return render_template('form_action.html', name=name, email=email,
comment=comment)
# Run the app :)
if __name__ == '__main__':
app.run(debug=True)
form_submit.html
// This page takes in the initial information via the text boxes and
passes the information to the python file above
Python
PYTHON PAGEPlease fill in your details
below and your comment to join the discussion
Please
enter your name:
Please
enter your email:
Please
enter your comment:
form_action.html
// I'm trying to get the information to pass to this page. The text boxes
from the previous html page remain on this html page as I want to
continue to add comments without having to go back to form_submit.html
each time
Python
PYTHON PAGEPlease fill in your details
below and your comment to join the discussion
Please
enter your name:
Please
enter your email:
Please
enter your comment:
// I included this bit as an original attempt to post a single comment
to the page(it will display while still passing the info to the text
file via python)
{{name}} ({{email}}):
{{comment}}
2016-12-03
Charles
+0
这是什么意思?你想达到什么目的? –
+1
本质上,我试图实现的目标是能够基于用户输入到文本字段(名称,电子邮件,评论)中的内容在网页上显示一些评论,类似于非常基本的排序论坛。所以基本上,例如,joe bloggs输入他的详细信息之后; “Joe Bloggs([email protected])我爱Python”,将会显示。接下来,Jane Doe可能会出现并添加一条可以阅读的评论; “Jane Doe([email protected])我也爱Python”,将会显示。这是否更有意义? –
+0
如通常所示,如果您需要多个元素,则必须创建包含元素的列表。然后将此列表发送到模板并使用模板'for'功能显示此列表中的元素。 –