必须重新启动 apache 服务器才能在 Flask 中显示来自 SQL 服务器的数据

Have to restart apache server to display data from SQL Server in Flask

我在 VPS 上设置了一个 Flask 应用程序,一切似乎都运行良好; 当我重新启动 apache 时,一切正常,我得到了这个: html table

如果我重新加载浏览器页面数据消失,只剩下table header;如果我想再次查看数据,我必须重新启动 apache 服务器,这是我无法解决的大问题

我的数据结构如下:

|----FlaskApp
|---------FlaskApp
|         +----main.html
|--------------static
|--------------templates
|              +----elenco.py
|              +----__init__.py

我尝试做的是使用 _mssql 连接到 SQL 服务器数据库,查询数据库并在 html table 中显示结果。 这是文件的内容:

init.py

from flask import Flask, render_template
import _mssql
from elenco  import Elenco_chiamate


Chiamate = Elenco_chiamate()


app = Flask(__name__)

@app.route('/')
def homepage():
    return render_template("main.html", chiamate_html = Chiamate)

if __name__ == "__main__":
    app.run()

elenco.py

    import _mssql

def Elenco_chiamate():
    conn = _mssql.connect(server='xxxxxxx', user='xxxxx', password='xxxxx')
    conn.execute_row('SELECT TOP 100 * FROM ASSET_VIEW')
    return conn 
    conn.close()

main.html

 <!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title>Python Programming Tutorials</title>
    <script
    src="https://code.jquery.com/jquery-3.1.1.min.js"
    integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="
    crossorigin="anonymous"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body>
    <table class="table table-striped table-bordered table-hover table-condensed">
        <tr>
        <th>
            INVENTARIO
        </th>
        <th>
            SERIALE
        </th>
        <th>
            APPARECCHIATURA
        </th>
        </tr>
    {% for row in chiamate_html %}
        <tr>
        <td>{{row['NUM']}}</td>
        <td>{{row['N_SERI']}}</td>
        <td>{{row['NOM']}}</td>
        </tr>
           {% endfor %}

    </table>
 </body>

</html>

您正在模块级别调用 Elenco_chiamate(),因此它只会被调用一次 - 当模块首次导入时。

改为在视图函数中调用它。