Python-MySQL中的错误处理

我正在运行一个基于python flask的web服务,我想在那里执行一个小的MySQL Query.当我获得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吗?如果你在回溯中读到,你会注意到你的错误来自于调用__getitem __()on None(nb:__ getitem __()是下标operator []的实现),这意味着如果你没有匹配的行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:要么记录异常(使用标准的日志记录包和logger.exception())并重新引发它们,要么简单地让它们传播(最终有一个更高级别的组件来处理记录未处理的异常):

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

finally:
    conn.close()

最后:构建sql查询的方式是utterly unsafe.使用sql占位符代替:

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

转载注明原文:Python-MySQL中的错误处理 - 代码日志