python - 加载我的数据库页面(Flask/Heroku)时如何修复内部服务器错误?

标签 python postgresql heroku flask internal-server-error

我有一个非常基本的 Heroku 网络应用程序,您可以在其中单击链接(在主页上)以重定向到其他页面。我这样做是为了测试数据库页面。当我单击以查看数据库页面时,所有页面都可以正常工作。当我尝试时收到一条错误消息:

Internal Server Error
The server encountered an internal error and was unable to complete your request.
Either the server is overloaded or there is an error in the application.

我确实尝试使用 procfile,但最终没有任何效果。我当前的 proctfile 如下所示:

web: gunicorn flask-sqlalchemy-test-02.wsgi:application --log-file=-

老实说,我不太确定是 app.py 中的 procfile 还是语法导致了我的问题。

我的 app.py 文件:

import os
import psycopg2
from flask import Flask, render_template, g, url_for

app = Flask(__name__)
DATABASE_URL = os.environ.get('postgres://fikwczdiymxhwf:73bf42c2c8a15fa59b77e93654b6383e1cf4f85bdf0156818d1cf39a77815f13@ec2-54-243-47-196.compute-1.amazonaws.com:5432/d3uburco4fea1b'

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/page2')
def page_2():
    return render_template("random_page_2.html")

@app.route('/hello')
def hello():
    return render_template("hello.html")

@app.route('/view_database')
def view_db():
    conn = psycopg2.connect(DATABASE_URL)
    db = conn.cursor()
    data = db.execute("SELECT * FROM example").fetchall()
    db.close()
    conn.close()
    return render_template('view_database.html', data=data)

我希望以无序列表的形式查看数据库,但却收到一条错误消息:

Internal Server Error
The server encountered an internal error and was unable to complete your request.
Either the server is overloaded or there is an error in the application.

最佳答案

您使用 os.environ.get() 的方式是错误的。

os.environ.get() 用于获取操作系统导出的环境变量,所以 DATABASE_URL 返回 None,你不能连接到 None URL,所以内部服务器错误。

**正确的方式:** 首先,导出环境变量,如果使用 Linux:

export DATABASE_URL=postgres://fikwczdiymxhwf:73bf42c2c8a15fa59b77e93654b6383e1cf4f85bdf0156818d1cf39a77815f13@ec2-54-243-47-196.compute-1.amazonaws.com:5432/d3uburco4fea1b

然后,在您的代码中,将该行替换为:

DATABASE_URL = os.environ.get('DATABASE_URL', '')

关于python - 加载我的数据库页面(Flask/Heroku)时如何修复内部服务器错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57306381/

相关文章:

django - 使用 Heroku 的关系 django_migrations 的权限被拒绝

从 Bash 调用的 Python 脚本不执行任何操作

python - 结果(Python)中的 "u"是什么?

sql - 在 postgresql 的单个查询中使用 WITH + DELETE 子句

postgresql - TypeORM 迁移 :generate working great except for DROP

ssl - Heroku 更新 SSL 端点失败 - 未找到签署证书的 key

css - 媒体查询适用于 chrome 但不适用于我的移动设备

python - 获取 pandas 中包含字符串的列数

Python语音识别API响应很慢

sql - 使用选定的列创建另一个字符串插值组合 Postgresql 中的所有字段?