【问题标题】:Displaying data on new page in Python在 Python 中的新页面上显示数据
【发布时间】:2016-09-30 06:43:59
【问题描述】:

我想在以下 index.html 页面的 <td> 中显示数据库中的每一行:

$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>address</th>
        <th>number</th>
    </tr>

    <tr>
        <td>//want name here</td>
        <td>//address here</td>
        <td>//number here</td>
    </tr>
</table>

app.py 代码:

import web
import MySQLdb

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        return render.hello_form()

    def POST(self):
            form = web.input(name="a", newname="s", number="d")
            conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
            x = conn.cursor()
            x.execute("SELECT * FROM details  WHERE name = '%s'" % (form.name))
            conn.commit()
            items = x.fetchall()
            for row in items: 
                conn.rollback()
                conn.close()
                return render.index(items)
    if __name__ == "__main__":
        app.run()

【问题讨论】:

  • 我在这里看到的是 SQL 注入吗?
  • 我没听懂你..?@aif
  • 如果 name = ' union select concat(login, ':', password) from users where user='admin 会发生什么? (是的,那是伪代码)见owasp.org/index.php/SQL_Injection

标签: python python-2.7 web.py


【解决方案1】:

items(获取的结果)将是一个元组数组。按原样返回数组,因为您希望在 html 上显示整个数据,并且 HTML 仅呈现一次。

app.py 代码

import web
import MySQLdb

urls = (
  '/', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
    def GET(self):
        return render.hello_form()

def POST(self):
        form = web.input(name="a", newname="s", number="d")
        conn = MySQLdb.connect(host= "localhost", user="root", passwd="", db="testdb")
        x = conn.cursor()
        x.execute("SELECT * FROM details  WHERE name = '%s'" % (form.name))
        items = x.fetchall()       
        conn.close()
        return render.index(items) // return the array of results as a whole
if __name__ == "__main__":
    app.run()

在 index.html 上

$def with(items)
<h1></h1>
<br/>
<br>
<table border="1">
    <tr>
        <th>Name</th>
        <th>address</th>
        <th>number</th>
    </tr>
   $for row in items: 
        <tr>
        <td>$row[0]</td>
        <td>$row[1]</td>
        <td>$row[2]</td>
        </tr>
</table>

Iterate over the items and display them

【讨论】:

  • 它不显示任何内容,只是显示一个空白页面
  • 尝试检查是否获取了数据。在 app.py 中获取项目后尝试打印项目并渲染一个不同的模板,该模板将按原样打印所有项目。渲染新模板:$def with (items) $items
  • 我认为没有获取数据,所以我应该怎么做在 python 中是全新的
  • app.py 中的打印项目打印什么?如果不打印任何内容,则 MYSQL 连接或查询有问题。检查这个答案stackoverflow.com/a/622308/5027503
  • 我给&lt;td&gt;$item&lt;/td&gt;时它正在打印,但它混合在一起,所以我认为sql没有问题
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多