【问题标题】:Apache web server Segmentation Fault error when connecting to a Postgres Database连接到 Postgres 数据库时出现 Apache Web 服务器分段错误错误
【发布时间】:2020-05-10 16:42:08
【问题描述】:

我有一个在 apache 服务器上运行的 python flask web 应用程序。 flask 应用程序只是一个函数,它返回我从 postgres 数据库中获得的值。

@app.route('/')
def hello_world():
    import psycopg2
    db_conn_string = ("dbname=" + "xxx"
                        + " user=" + "xxx"
                        + " host=" + "xxx"
                        + " password=" + "xxx")
    db_connection = psycopg2.connect(db_conn_string)
    cursor = db_connection.cursor()
    cursor.execute("SELECT * FROM XXX")
    return cursor.fetchall()

当我运行这个应用程序时,我会在浏览器上看到这个:

我查看了/var/log/apache2/error.log下的日志,错误是:

[Fri Jan 24 10:34:34.676561 2020] [core:notice] [pid 15644:tid 139639322680256] AH00051: child pid 15972 exit signal Segmentation fault (11), possible coredump in /etc/apache2

有趣的是,当我将 return 语句更改为只返回一个 hello world 时,它运行得很好,而且我没有看到任何错误。所以我的假设是错误是由于 apache web 应用程序试图连接到 postgres 数据库。我检查了数据库的凭据,那里没有任何问题。我不知道如何解决这个问题。

编辑:具有相同代码的测试 python 程序可以工作,我能够检索数据。

【问题讨论】:

  • 在 Python 测试程序中运行函数会得到什么结果?
  • @Bodo 是的,具有相同代码的 python 程序可以工作,我能够连接到数据库并检索数据。
  • cursor.fetchall() 返回一个元组列表。我猜调用函数没有准备好处理那种结果。
  • @ArchitVerma 请edit 您的问题并在那里添加所有信息,而不是在 cmets 中回答。请展示正在运行的 Python 程序及其输出。
  • @tripleee 我认为这不是问题所在。即使尝试从列表中仅返回一个值,我也会收到相同的错误。

标签: python linux postgresql python-2.7 apache


【解决方案1】:

您的视图(即hello_world 函数)需要返回 Flask 支持的内容。也许看看Flask tutorial on Views 以获取更多示例

最简单的方法是将其转换为字符串并返回,例如:

import psycopg2

@app.route('/')
def hello_world():
    con = psycopg2.connect(db_conn_string)
    with con, con.cursor() as cur:
        cur.execute("SELECT * from xxx;")
        result = cur.fetchall()
    return repr(result)

我已将您的代码重新安排得更传统一些。请注意,imports 通常位于顶部。您还想让连接字符串在顶部成为常量。使用 psycopg2 游标作为上下文管理器也可以很好地将它们包装在事务中,COMMITing 成功并执行 ROLLBACK 异常

【讨论】:

  • 感谢山姆的回答!我尝试从列表中只返回一个值,但没有帮助。我认为问题不在于 Flask 无法理解 return 语句。
  • 如果你在 Apache 之外运行烧瓶怎么办?即在教程中使用flask run
  • 它工作正常。代码本身似乎没有问题。不知何故,当我在 apache 服务器上运行它时,它给了我分段错误错误。
  • 然后可能让 apache 输出更多日志信息,以找出实际失败的位置/内容。也许更新问题以包含相关的配置设置
猜你喜欢
  • 1970-01-01
  • 2014-03-08
  • 2017-12-16
  • 2016-10-26
  • 2020-06-05
  • 1970-01-01
  • 2015-05-28
  • 1970-01-01
  • 2014-04-25
相关资源
最近更新 更多