使用数据库值构造动态HTML内容

时间:2019-04-17 12:45:39

标签: python html python-3.x postgresql

我想创建一个动态HTML页面,并将PostgresQL数据库中的值应用于HTML模板的必要位置。

下面的图像是HTML页面的一部分,我希望从数据库的值中填充这些区域,有没有办法做到这一点?还是有其他更好的方法可以做到这一点。

我正在使用Python和PostgreSQL数据库。

预先感谢

  import psycopg2
  import jinja2
  from collections import namedtuple
  TEMPLATE="""
     <!DOCTYPE html>
       <html><head><title>Jinja Template Example</title>
       <meta name="viewport" content="width=device-width, initial- 
  scale=1.0">
       <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" 
   rel="stylesheet" media="screen">
       <style type="text/css">
       .container {max-width: 500px;padding-top: 100px;}</style></head>
       <body>
        <div class="container">
         <p>My string: {{my_string}}</p>
         <p>Value from the list:</p>
         <p>Loop through the list:</p>
         <p style="line-height: 14px; text-align: center; font-size: 12px; margin: 0;"> Database Value </p><br>
         <p style="line-height: 14px;font-weight:Bold; text-align: center; font-size: 12px; margin: 0;">Database value</p>

         <ul>
           {% for row in test_records %}
           <li>{{ test_records.column1 }}</li>
           {% endfor %}
         </ul>
        </div>
          <script src="http://code.jquery.com/jquery-1.10.2.min.js"> 
          </script>
          <script src="http://netdna.bootstrapcdn.com/bootstr

          ap/3.0.0/js/bootstrap.min.js"></script>
          </body>
      </html>
      """
  def dB_Fetch():
  try:
   connection = psycopg2.connect(user="sandeep",
                                  password="postgres",
                                  host="127.0.0.1",
                                  port="5432",
                                  database="postgres")
   cursor = connection.cursor()
   postgreSQL_select_Query = "select * from test"
   cursor.execute(postgreSQL_select_Query)
   print("Selecting rows from test table using cursor.fetchall")
   test_records = cursor.fetchall()
   a = list();
   print("Print each row and it's columns values")
   for row in test_records:
       a.append(test_records);
       #print("column1 = ", row[0] )
       #print("column2 = ", row[1])
       print(a[0])

   env = jinja2.Environment()
   template = env.from_string(TEMPLATE)
   row_tuple = namedtuple("Row", [col[0] for col in cursor.description])
   result = template.render(rows=[row_tuple(row) for row in cursor.fetchall()])
   print (TEMPLATE)
   print (result)  

 except (Exception, psycopg2.Error) as error:
     print ("Error while fetching data from PostgreSQL", error)
 finally:
     if(connection):
         cursor.close()
         connection.close()
         print("PostgreSQL connection is closed")
   if __name__ == '__main__':
    dB_Fetch()
    enter code here

我在此代码中遇到错误,您能告诉我吗? enter image description here

2 个答案:

答案 0 :(得分:1)

解决此问题的最佳方法是使用Psycopg读取数据,然后使用一些模板引擎-例如jinja2-从数据库中生成HTML给定的数据。

更新

解决方案的草图可能看起来像这样(未经测试)。

import psycopg2
import jinja2
from collections import namedtuple

TEMPLATE="""
<html><head></head><body>
<ul>
{% for row in rows %}
  <li>{{ row.column1 }}, {{ row.column2 }}</li>
{% endfor %}
</ul>
</body></html>
"""

env = jinja2.Environment()
template = env.from_string(TEMPLATE)

with psycopg2.connect("dbname=test user=postgres") as conn:
    with conn.cursor() as curs:
        curs.execute("SELECT column1, column2 FROM test;")
        row_tuple = namedtuple("Row", [col[0] for col in curs.description])
        print(template.render(rows=[row_tuple(row) for row in curs.fetchall()]))

答案 1 :(得分:0)

代码样式必须如下所示。您可以使用jinja2搜索数据库应用程序。 只有更改,您才能在执行数据库查询后从列表中提供数据。

这是初学者的简单示例:

    <!DOCTYPE html>
<html>
  <head>
    <title>Flask Template Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <style type="text/css">
      .container {
        max-width: 500px;
        padding-top: 100px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <p>My string: {{my_string}}</p>
      <p>Value from the list: {{my_list[3]}}</p>
      <p>Loop through the list:</p>
      <ul>
        {% for n in my_list %}
        <li>{{n}}</li>
        {% endfor %}
      </ul>
    </div>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
  </body>
</html>