刷新页面时出现Flask错误(' NoneType')

时间:2017-10-25 16:33:26

标签: python mysql flask

亲爱的Python社区,

我遇到了一个无法解决的问题。我最近搬到了macOS Sierra版本10.12.6。

我所做的只是与MariaDB Mysql数据库连接。在启动程序时,初始连接和响应有效,因此所有输出都在那里,但是当我刷新页面时,我得到一个" TypeError:' NoneType'对象不可迭代"。如果我重新启动终端中的程序,它将再次工作 - 直到我刷新....

这里是代码:

from dbhelper2 import DBHelper


app = Flask(__name__)
DB = DBHelper()

@app.route('/trtdtable')
def trtdtable():
    try:
        tabledata = DB.table_inputs()
    except Exception as e:
        print(e)
        tabledata = None
    return render_template("trtdtable.html", tabledata=tabledata)

第二部分(数据库助手)

import pymysql

# Connect to the database
connection =  pymysql.connect(host='localhost',user='root',password='',db='test',cursorclass=pymysql.cursors.DictCursor)

class DBHelper:

    def table_inputs(self):
        try:
            query = "SELECT PersonID, LastName, FirstName, Address, City FROM persons";
            with connection.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute(query)
            return cursor.fetchall()
        finally:
            connection.close()

和HTML(" trtdtable.html"):

<table id="customers">
            <tr>
              <th>ID</th>
              <th>Last Name Name</th>
              <th>First Name</th>
              <th>Address</th>
              <th>City</th>
            </tr>

           {% for row in tabledata %}
           <tr>
             <td>{{ row['PersonID'] }}</td>
             <td>{{ row['LastName'] }}</td>
             <td>{{ row['FirstName'] }}</td>
             <td>{{ row['Address'] }}</td>
             <td>{{ row['City'] }}</td>
           </tr>
           {% endfor %}

   </table>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您在查询后关闭了连接。别这么做。

此外,永远不会捕获并吞下所有异常。如果你没有那个空白except,那么Flask会告诉你错误是什么。

相关问题