簡體   English   中英

連接到 Postgres 數據庫時出現 Apache Web 服務器分段錯誤錯誤

[英]Apache web server Segmentation Fault error when connecting to a Postgres Database

我有一個在 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 程序有效,我能夠檢索數據。

您的視圖(即hello_world函數)需要返回 Flask 支持的內容。 也許可以查看Flask 上Flask 教程以獲取更多示例

最簡單的方法就是將其轉換為字符串並返回,例如:

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)

我已經重新安排了您的代碼,使其更加傳統。 請注意, import通常位於頂部。 您還希望將連接字符串設為頂部的常量。 使用psycopg2游標作為上下文管理器也很好地將它們包裝在一個事務中,成功時COMMIT並在異常時執行ROLLBACK

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM