BoJ*_*man 12 python error-handling
我正在运行一个基于python flask的web服务,我想执行一个小的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
Run Code Online (Sandbox Code Playgroud)
我试图自己处理错误处理并将此代码用于我的项目,但似乎这不能正常工作.
#!/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)
Run Code Online (Sandbox Code Playgroud)
基本上我只想返回一个值,当一切正常工作时我想要什么都不返回,如果它不是最好在我的服务器上有错误消息.如何以正确的方式使用错误处理?
编辑更新了当前代码+错误消息.
bru*_*ers 24
第一点:你的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()
Run Code Online (Sandbox Code Playgroud)
现在你真的必须在这里捕获一个TypeError吗?如果你在阅读回溯,你会发现,你的错误来自调用__getitem__()上None(注意:__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()
Run Code Online (Sandbox Code Playgroud)
现在你真的需要在这里捕捉MySQL错误吗?您的查询应该经过充分测试,它只是一个读取操作,所以它不应该崩溃 - 所以如果你在这里出了问题,那么你显然有一个更大的问题,你不想把它隐藏在地毯下.IOW:要么记录异常(使用标准logging包logger.exception()),要么重新引发它们,或者更简单地让它们传播(最终有一个更高级别的组件负责记录未处理的异常):
try:
curs.execute(sql)
row = curs.fetchone()
if row:
return row[0]
return None
finally:
conn.close()
Run Code Online (Sandbox Code Playgroud)
最后:构建SQL查询的方式完全不安全.改为使用sql占位符:
q = "%s%%" % data["email"].strip()
sql = "select userid from oc_preferences where configkey='email' and configvalue like %s"
cursor.execute(sql, [q,])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58882 次 |
| 最近记录: |