Python-MySQL 中的错误处理 [英] Error handling in Python-MySQL

查看:19
本文介绍了Python-MySQL 中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个基于 python flask 的小网络服务,我想在其中执行一个小的 MySQL 查询.当我为我的 SQL 查询获得有效输入时,一切都按预期工作,并且我得到了正确的值.但是,如果该值未存储在数据库中,我会收到 TypeError

I am running a little webservice based on python flask, where I want to execute a small MySQL Query. When I get a valid input for my SQL query, everything is working as expected and I get the right value back. However, if the value is not stored in the database I receive a 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

我尝试自己进行错误处理并将此代码用于我的项目,但似乎无法正常工作.

I tried to tap into error handling myself and use this code for my project, but it seems like this doesn't work properly.

#!/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)

基本上我只想返回一个值,当一切正常时,如果我的服务器上没有错误消息,我不想返回任何内容.如何以正确的方式使用错误处理?

Basically I just want to return a value, when everything is working properly and I want to return nothing if it isn't preferably with an error message on my server. How can I use error handling in a proper way?

EDIT 更新了当前代码 + 错误消息.

EDIT Updated current code + error message.

推荐答案

第一点:你的 try/except 块中有太多代码.当您有两个可能引发不同错误的语句(或两组语句)时,最好使用不同的 try/except 块:

First point: you have too much code in your try/except block. Better to use distinct try/except blocks when you have two statements (or two groups of statements) that may raise different errors:

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() 的返回:

Now do you really have to catch a TypeError here ? If you read at the traceback, you'll notice that your error comes from calling __getitem__() on None (nb : __getitem__() is implementation for the subscript operator []), which means that if you have no matching rows cursor.fetchone() returns None, so you can just test the return of 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())并重新引发它们,或者更简单地让它们传播(并最终有更高的级别组件负责记录未处理的异常):

Now do you really need to catch MySQL errors here ? Your query is supposed to be well tested and it's only a read operation so it should not crash - so if you have something going wrong here then you obviously have a bigger problem, and you don't want to hide it under the carpet. IOW: either log the exceptions (using the standard logging package and logger.exception()) and re-raise them or more simply let them propagate (and eventually have an higher level component take care of logging unhandled exceptions):

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

finally:
    conn.close()

最后:构建 sql 查询的方式完全不安全.改用 sql 占位符:

And finally: the way you build your sql query is utterly unsafe. Use sql placeholders instead:

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.烧瓶视图应该返回可用作 HTTP 响应的内容,而 None 在这里不是有效选项.

Oh and yes: wrt/ the "View function did not return a response" ValueError, it's because, well, your view returns None in many places. A flask view is supposed to return something that can be used as a HTTP response, and None is not a valid option here.

这篇关于Python-MySQL 中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆