簡體   English   中英

Python-MySQL 中的錯誤處理

[英]Error handling in Python-MySQL

我正在運行一個基於 python flask 的小網絡服務,我想在其中執行一個小的 MySQL 查詢。 當我獲得 SQL 查詢的有效輸入時,一切都按預期工作,並且我得到了正確的值。 但是,如果該值未存儲在數據庫中,我會收到TypeError

    Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1478, in full_dispatch_request
    response = self.make_response(rv)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1566, in make_response
    raise ValueError('View function did not return a response')
ValueError: View function did not return a response

我嘗試自己進行錯誤處理並將此代碼用於我的項目,但似乎這無法正常工作。

#!/usr/bin/python

from flask import Flask, request
import MySQLdb

import json

app = Flask(__name__)


@app.route("/get_user", methods=["POST"])
def get_user():
    data = json.loads(request.data)
    email = data["email"]

    sql = "SELECT userid FROM oc_preferences WHERE configkey='email' AND configvalue LIKE '" + email + "%';";

    conn = MySQLdb.connect( host="localhost",
                            user="root",
                            passwd="ubuntu",
                            db="owncloud",
                            port=3306)
    curs = conn.cursor()

    try:
        curs.execute(sql)
        user = curs.fetchone()[0]
        return user
    except MySQLdb.Error, e:
        try:
            print "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
            return None
        except IndexError:
            print "MySQL Error: %s" % str(e)
            return None
    except TypeError, e:
        print(e)
        return None
    except ValueError, e:
        print(e)
        return None
    finally:
        curs.close()
        conn.close()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)

基本上我只想返回一個值,當一切正常時,如果我的服務器上沒有錯誤消息,我不想返回任何內容。 如何以正確的方式使用錯誤處理?

編輯更新當前代碼 + 錯誤消息。

第一點:你的 try/except 塊中有太多代碼。 當您有兩個可能引發不同錯誤的語句(或兩組語句)時,最好使用不同的 try/except 塊:

try:
    try:
        curs.execute(sql)
        # NB : you won't get an IntegrityError when reading
    except (MySQLdb.Error, MySQLdb.Warning) as e:
        print(e)
        return None

    try: 
        user = curs.fetchone()[0]
        return user
    except TypeError as e:
        print(e)
        return None

finally:
    conn.close()

現在您真的必須在這里捕獲 TypeError 嗎? 如果您閱讀回溯,您會注意到您的錯誤來自在None上調用__getitem__() (nb: __getitem__()是下標運算符[] ),這意味着如果您沒有匹配的行cursor.fetchone()返回None ,因此您可以測試currsor.fetchone()的返回:

try:
    try:
        curs.execute(sql)
        # NB : you won't get an IntegrityError when reading
    except (MySQLdb.Error, MySQLdb.Warning) as e:
        print(e)
        return None

    row = curs.fetchone()
    if row:
        return row[0]
    return None

finally:
    conn.close()

現在您真的需要在這里捕獲 MySQL 錯誤嗎? 您的查詢應該經過良好測試,並且它只是一個讀取操作,因此它不應該崩潰 - 所以如果您在這里出現問題,那么您顯然有一個更大的問題,並且您不想將其隱藏在地毯下。 IOW:要么記錄異常(使用標准logging包和logger.exception() )並重新引發它們,或者更簡單地讓它們傳播(並最終讓更高級別的組件負責記錄未處理的異常):

try:
    curs.execute(sql)
    row = curs.fetchone()
    if row:
        return row[0]
    return None

finally:
    conn.close()

最后:您構建 sql 查詢的方式是完全不安全的 改用 sql 占位符:

q = "%s%%" % data["email"].strip() 
sql = "select userid from oc_preferences where configkey='email' and configvalue like %s"
cursor.execute(sql, [q,])

哦,是的:wrt/“視圖函數沒有返回響應”ValueError,這是因為,你的視圖在很多地方都返回None Flask 視圖應該返回一些可以用作 HTTP 響應的東西,這里None不是一個有效的選項。

暫無
暫無

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

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