如何解决运行的 Flask Web 应用程序上的 500 HTTP 错误

问题描述 投票:0回答:1

我的 Flask Web 应用程序遇到问题,我正在尝试运行该应用程序,但无论如何都会出现 500 错误。这是我的网络应用程序:

import redis, sqlite3, time
from flask import Flask, render_template, request, g, current_app
from sqlite3 import DatabaseError

app = Flask(__name__)

r = redis.Redis(host='localhost', port=6379, db=0)

conn = sqlite3.connect('trade.db')
cursor = conn.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS signals (
        timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, 
        ticker,
        order_action,
        order_contracts,
        order_price
    )
""")
conn.commit()

def get_db():
    if 'db' not in g:
        g.db = sqlite3.connect('trade.db')
        g.db.row_factory = sqlite3.Row

    return g.db

@app.get('/')
def dashboard():
    db = get_db()
    cursor = db.cursor()
    cursor.execute("""
        SELECT * FROM signals
    """)
    signals = cursor.fetchall()

    return render_template('dashboard.html', signals=signals)

try:
    r=redis.Redis(host='localhost', port=6379, db=0)
except redis.RedisError as e:
    print(f"Error: Could not connect to the Redis server")

@app.post("/webhook")
def webhook():
    data = request.data

    if data:
        r.publish('tradingview', data)

        data_dict = request.json

        db = get_db()
        cursor = db.cursor()
        cursor.execute("""
            INSERT INTO signals (ticker, order_action, order_contracts, order_price) 
            VALUES (?, ?, ?, ?)
        """, (data_dict['ticker'], 
                data_dict['strategy']['order_action'], 
                data_dict['strategy']['order_contracts'],
                data_dict['strategy']['order_price']))

        db.commit()

        return data
    

    return {
        "code": "success"
    }

@app.errorhandler(DatabaseError)
def special_exception_handler(error):
    return 'Database connection failed', 500

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

这是我的模板:

<html>
    <head>
        <title>dashboard</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    </head>

    <body>
        <div class="container">
            <h1>Signals</h1>
            <table class="table">
                <tr>
                    <th>timestamp</th>
                    <th>ticker</th>
                    <th>action</th>
                    <th>quantity</th>
                    <th>price</th>
                </tr>
                {% for signal in signals %}
                <tr>
                    <td>{{ signal.timestamp }}</td>
                    <td>{{ signal.ticker }}</td>
                    <td>{{ signal.order_action }}</td>
                    <td>{{ signal.order_contracts }}</td>
                    <td>{{ signal.order_price }}</td>
                </tr>
                {% endfor %}
            </table>
        </div>
    </body>
</html>

这是错误日志:

 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
[2024-01-05 20:14:16,117] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 869, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 867, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 852, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "C:\Users\lenovo\Desktop\IB TV Automated Trading\webapp.py", line 37, in dashboard
    return render_template('dashboard.html', signals=signals)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\templating.py", line 151, in render_template
    template = app.jinja_env.get_or_select_template(template_name_or_list)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\jinja2\environment.py", line 1081, in get_or_select_template
    return self.get_template(template_name_or_list, parent, globals)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\jinja2\environment.py", line 1010, in get_template
    return self._load_template(name, globals)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\jinja2\environment.py", line 969, in _load_template
    template = self.loader.load(self, name, self.make_globals(globals))
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\jinja2\loaders.py", line 126, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\templating.py", line 65, in get_source
    return self._get_source_fast(environment, template)
  File "C:\Users\lenovo\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\templating.py", line 99, in _get_source_fast
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: dashboard.html
127.0.0.1 - - [05/Jan/2024 20:14:16] "GET / HTTP/1.1" 500 -

这是错误: 500 HTTP error

感谢您的关注。

我尝试了 Flask 文档推荐的“DatabaseError”错误处理,我希望解决这个问题,这样我就可以运行我的 web 应用程序

python sqlite flask redis http-status-code-500
1个回答
0
投票

您的错误日志表明出现问题是因为找不到您的模板“dashboard.html”:

jinja2.exceptions.TemplateNotFound: dashboard.html

您确定该文件位于应有的位置吗?

© www.soinside.com 2019 - 2024. All rights reserved.