【问题标题】:How to fix R1710 Either all return statements in a function should return an expression, or none of them should.?如何修复 R1710 函数中的所有 return 语句都应该返回一个表达式,或者它们都不应该。?
【发布时间】:2020-05-06 15:02:46
【问题描述】:

我在我的代码上使用pylint 并收到错误

R1710:函数中的所有 return 语句都应该返回一个表达式,或者它们都不应该返回。 (不一致的返回语句)

只有两种可能的返回语句,如果我没记错的话,它们都返回表达式

@api_view(["GET", "POST"])
def user_info(request):
    if request.method == 'GET':
        username = request.GET.get("username")
        password = request.GET.get("password")

        return JsonResponse(error_handle(serialize(username, password)))

    if request.method == 'POST':
        username = request.data["username"]
        password = request.data["password"]

        return JsonResponse(error_handle(serialize(username, password)))
def error_handle(serializer):
   error = serializer["error"].value
   if error > 0:
       return {"success": "false", "internal_code": error}
   return {"success": "true",
           "account_token": serializer.data["account_token"],
           "user_id": serializer.data["id"],
           "account_name": serializer.data["account_name"],
           "account_permission": serializer.data["account_permission"],
           "pin": serializer.data["pin"]
           }


def serialize(user, password):
   data = Account.objects.get(username=user, password=password)
   return AccountSerializer(data)

【问题讨论】:

  • 如果request.method 既不是GET 也不是POST,在user_info 中会发生什么?
  • 就是这样,谢谢

标签: python django error-handling pylint


【解决方案1】:

如果request.method 既不是GET 也不是POST,那么user_info 会发生什么?

@api_view(["GET", "POST"])
def user_info(request):
    if request.method == 'GET':
        # ...
        return JsonResponse(error_handle(serialize(username, password)))

    if request.method == 'POST':
        # ..
        return JsonResponse(error_handle(serialize(username, password)))

    # ???
    # Something should be returned here!

原则上,可能会引发异常“405 - Method Not Allowed”。但是由于装饰器已经限制了请求的可能方法,所以它是无法访问的代码。 Pylint 可能无法知道它是无法访问的代码。

【讨论】:

  • 我可以用Something should be returned here! 代替raise e吗?
  • @alper 我猜在这种情况下应该引发“405 - Method Not Allowed”异常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2010-09-07
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多