【问题标题】:Is it possible to print the data from a text file to a html page via javascript or python(Flask)?是否可以通过 javascript 或 python(Flask) 将文本文件中的数据打印到 html 页面?
【发布时间】:2016-12-03 01:04:00
【问题描述】:

我正在研究 python 并在服务器上运行它(在本例中为 Flask)。基本上我试图将本地文本文件的一些内容打印到 html 页面。我从用户那里获取一些输入值(姓名、电子邮件和评论),并将它们逐行存储到本地文本文件中。目前,我可以获得要在页面上打印的最新输入(即评论、用户的姓名和电子邮件),但每次重新提交表单时都会被替换。我现在有点在搞乱它(例如,我从文件读取并打印了 5 个用户输入实例到服务器)。但是,我正在尝试将姓名、电子邮件和 cmets 打印到 form_action.html 页面上,并保留所有以前的 cmets。正如我所说,我可以打印内容,并且它们显示在 cmd 提示符中,但是这可以通过 javascript 完成,因此它可以显示在 html 页面上,或者可以使用 python 使用不同的方式完成。我正在使用的书没有介绍如何做,我在网上找不到任何东西。谁能治愈我的好奇心?如果我没有意义,请问我,我很乐意详细说明。干杯!

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 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

 <html>
 <body style="background-color: #3DC247;">

 <head>
 <title>Python</title>
 </head>
 <body>

  <div align = "center">
  <h1 style="font-family:verdana;">PYTHON PAGE</h1>

  <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">    
  <br>
              <input type="submit" /><br>
            </form>
        </div>
        
  </body>
  </html>

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

  <html>

  <body style="background-color: #3DC247;">

  <head>
  <title>Python</title>
   </head>

   <div align = "center">

   <h1 style="font-family:verdana;">PYTHON PAGE</h1>


   <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">    
    <br>
              <input type="submit" /><br>
            </form>
    // 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)
    <body>
    <div id="container">
        <div class="title">
            <p></p>
        </div>
        <div id="content">
            <strong>{{name}} ({{email}}):</strong><br>
            {{comment}}
        </div> 
        </div>
      </body>   
   </html>

【问题讨论】:

  • 这是什么意思?你想达到什么目的?
  • 基本上我想要实现的是能够根据用户在文本字段中输入的内容(名称、电子邮件、评论)在网页上显示许多 cmets,类似于各种非常基本的论坛。所以基本上,例如,在 joe bloggs 输入他的详细信息之后;将显示“Joe Bloggs (jbloggs@gmail.com) 我爱 Python”。接下来,Jane Doe 可以出现并添加一条评论,该评论将显示为;将显示“Jane Doe (jdoe@gmail.com) 我也喜欢 Python”。这是否更有意义?
  • 像往常一样,如果您需要多个元素,那么您必须创建包含元素的列表。然后将此列表发送到模板并使用模板for 函数显示此列表中的元素。

标签: javascript python html


【解决方案1】:

在您的 GET 路由“(”/“)”中,您需要从文件中读取所有 cmets,然后执行 render_template 并将这些传递给 form_submit 模板。

然后,在 form_submit 模板中,您将遍历这些 cmets 并在该循环中为每个 cmets 呈现 html。

我不太熟悉 flask 是如何做事的,但这似乎是模板化网络应用程序中最合乎逻辑的方式。

实际上,这里不需要两个模板。在 POST 路由 ('/hello') 中,您应该将其重定向回根目录 "("/")" 并让它再次处理渲染。

此外,我建议不必为本质上相同的资源使用不同的路线。 "/" 可以同时接受初始 GET,然后是 POST。但只能在最后这样做......

【讨论】:

    【解决方案2】:

    您正在读取和写入文件,但在模板中您只获得了姓氏或条目,因为您没有将从文件中读取的内容存储在列表中。 尝试以下方式:

    f = open("user+comments.txt", "a")
    
    f.write(name + ':' + email + ':' + comment)
    f.write('\n')
    f.close()
    
    details = []
    # 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
            try:
                details.append(lines[0].split(':'))
            except:
                'List cannot be populated'
    f.close()
    
    return render_template('form_action.html', details=details) # return details list containing user, email, comment
    

    我添加了“:”作为姓名、电子邮件和评论之间的分隔符,因此更容易拆分条目

    现在返回的“详细信息”包含模板所需的所有内容。

    但是在模板内部,你也需要一个循环,在 Flask 中是这样的:

    {% for user, email, comment in details %}
                            User: {{ user }} <br/>
                            Email: {{ email }} <br/>
                            Comment: {{ comment }} <br/>
                        {% endfor %}
    

    and the screenshot from your html output

    您还需要反转条目,以便显示最后 5 个, 希望有帮助!

    【讨论】:

    • 这绝对是我要找的,谢谢!知道为什么它可能会导致以下错误:ValueError: not enough values to unpack (expected 3, got 1)
    • 只尝试“解包”一个,看看它是什么,所以不要使用名称,电子邮件,评论只使用名称作为循环。当您从列表中请求的元素多于实际存在的元素时,就会发生此错误。
    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多