【问题标题】:Try except inside a function doesn't work but outside does尝试 except 在函数内部不起作用,但在外部起作用
【发布时间】:2020-05-08 08:21:07
【问题描述】:

我正在尝试将 try except 块作为 DRY 的一部分从我的函数之外获取。如果我将它直接放入函数中它可以工作

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

    try:
        Account.objects.get(username=username, password=password)
    except Account.DoesNotExist:
        return JsonResponse({
            "success": "false",
            "error_code": "1",
        })

但是如果我把它变成函数user_check它就不起作用了

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

        user_check(username,password)
def user_check(username,password):
    try:
        Account.objects.get(username=username, password=password)
    except Account.DoesNotExist:
        return JsonResponse({
            "success": "false",
            "error_code": "1",
        })

【问题讨论】:

    标签: python django django-rest-framework try-catch


    【解决方案1】:

    也从 try 块返回。喜欢:

    def user_check(username,password):
        try:
            Account.objects.get(username=username, password=password)
            # Add this line
            return True
        except Account.DoesNotExist:
            return JsonResponse({
                "success": "false",
                "error_code": "1",
            })
    

    而且,您的功能可能是:

    @api_view(["GET", "POST"])
    def user_info(request):
        if request.method == "GET":
            username = request.GET.get("username")
            password = request.GET.get("password")
    
            data = user_check(username, password)
            if data==True:
                # executed from try block known
    

    【讨论】:

    • 这也不起作用,因为除了不返回 JsonResponse 而是
    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    相关资源
    最近更新 更多