简体   繁体   English

在Python中检查函数的返回值

[英]Checking for the return value of a function in Python

I have a small function for database connection in Django as follows: 我在Django中有一个用于数据库连接的小功能,如下所示:

def db_connection(query_name):
    try:
        cursor = connection.cursor()
        cursor.execute(query_name)
        descr = cursor.description
        rows = cursor.fetchall()
        result = [dict(zip([column[0] for column in descr], row)) for row in rows]
        return result
    except Exception as e:
        return e 
    finally:
       cursor.close()

This function is used in my function views for Django rest framework to execute SQL queries.The general syntax is as follows: 在我的Django Rest框架的函数视图中使用此函数来执行SQL查询。常规语法如下:

@api_view(['GET'])
def foo_bar(request):
    ....
    ....
    ....
    query1 = "Select name from table"
    result = db_connection(query1)

    return Response(result, status=status.HTTP_200_OK)

However,what I need is to change the status value in the Response tuple depending on the return value of my db_connection function ie to return a 200 OK if no exception occurs else a 500. How can I check if the return value of a function is an exception ? 但是,我需要根据db_connection函数的返回值更改Response元组中的状态值,即如果没有异常,则返回200 OK,否则返回500。如何检查函数的返回值是否是有例外吗?

You are explicitly bypassing all the nice control flow that exceptions already give you. 您显式地绕过了异常已经给您的所有不错的控制流。 Don't do that. 不要那样做

If you just want a 500 to be returned, then don't catch the exception at all; 如果您只想返回500,则根本不要捕获异常。 just let it bubble up, Django's exception handling middleware will catch it and return a 500 response. 只是让它冒出来,Django的异常处理中间件将捕获它并返回500响应。

In any case, you should never catch the base Exception class; 在任何情况下,您都不应捕获基础Exception类。 only catch the things you can actually deal with. 只抓住你可以实际处理的东西。 And when you do catch an exception, you should actually deal with it; 当您确实捕获到异常时,您应该实际处理它; returning it instead of raising it is of no use whatsoever. 返回它而不是提高它没有任何用处。

I would move the try catch block in the foo_bar function over the result = db_connection(query1) code and return a 500 status from there, along with some kind of errors dict which contains a message explaining why it failed. 我将把foo_bar函数中的try catch块移到result = db_connection(query1)代码上,并从那里返回500状态,以及某种错误dict,其中包含说明失败原因的消息。 I say this because I'm assuming you are making a REST API which must always return an answer and not crash the normal django way. 我之所以这样说,是因为我假设您正在制作一个REST API,该API必须始终返回一个答案并且不会使django正常崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM