0

I'm trying to return a variable (list) in python but it does not allows me to return it. Instead it goes into except block and returns somethhing else.

The code is like this: Initially I'm getting period_value(datetime), search_name(location name) and time_period(day,week,month,year) via Ajax calls. If its day, then its work fine, but in other cases(week,month,year) the result variable does gives me satisfied data but it does not returns the data and instead goes into except and returns something else. This seems to be a weird problem. Kindly check where I'm going wrong?

if request.POST.has_key('period_val') or request.POST.has_key('search_name'):
    try : period_val = request.POST['period_val']
    except : period_val = datetime.datetime.strftime((datetime.date.today()), '%m/%d/%Y')

    try: time_period = request.POST['time_period']
    except : time_period = 'day'

    try : search_name = request.POST['search_name']
    except : search_name = ""

    return HttpResponse(json.dumps(get_widgets_data(request,period_val,time_period,search_name)), mimetype = "application/json")

get_widgets_data functions

def get_widgets_data(request,period_val,time_period,search_name):

    if time_period == 'day':
        file_name = datetime.datetime.strptime(period_val, '%m/%d/%Y')
        current_file_name = file_name.strftime("%Y-%m-%d.json")
        yester_date = file_name - timedelta(days = 1)
        yester_file_name = yester_date.strftime("%Y-%m-%d.json")

    elif time_period == 'week':
        file_name = str(period_val).split(", ")
        current_file_name = file_name[1] + "-w" + file_name[0].split(" ")[0]+".json"

        if (int(file_name[0].split(" ")[0]) - 1) <= 0:
            year = int(file_name[1]) - 1 
            week = datetime.date(year,12,31).isocalendar()[-1]
            yester_file_name = file_name[1] + "-w" + file_name[0]+".json"
        else :
            yester_file_name = file_name[1] + "-w" + str(int(file_name[0].split(" ")[0]) - 1)+".json"

    elif time_period == 'month':
        file_name = datetime.datetime.strptime(period_val, '%B, %Y')
        current_file_name = file_name.strftime("%Y-%m.json")
        yester_month = int((current_file_name.split(".")[0]).split("-")[1]) - 1
        yester_year = int((current_file_name.split(".")[0]).split("-")[0])

        if yester_month == 0:
            yester_year = yester_year - 1
            yester_month = 12

        yester_file_name = str(yester_year) + "-" + str(yester_month) + ".json"

    elif time_period == 'year':
        file_name = datetime.datetime.strptime(period_val, '%Y')
        current_file_name = file_name.strftime("%Y.json")
        yester_file_name = str(int(period_val)-1) + ".json"

    with open( os.path.join(os.path.dirname(__file__),'../../../../service/report/data/processed/Akamai/energy_meter/',current_file_name)) as file_handler:
        current_file_content = json.load(file_handler)
    file_handler.close()

    user_level_mapping = UserLevelMapping.objects.filter(user_id=request.user.id)
    level = (user_level_mapping[0].level_id).split(':')[0]
    l_id = (user_level_mapping[0].level_id).split(':')[1]

    try : # try if this file exists or not else goes into except.
        with open( os.path.join(os.path.dirname(__file__),'../../../../service/report/data/processed/Akamai/energy_meter/',yester_file_name)) as file_handler:
            yester_file_content = json.load(file_handler)
        file_handler.close()

        device_level_mapping_values = device_level_mapping_func(level,l_id)
        yester_time = list()
        yester_file_datetime = yester_file_content["device"].keys()
        yester_total = 0.0

        for time in yester_file_datetime:
            yester_time.append(time.split(" ")[1])

        for date_time in current_file_content["device"].keys():
            time = date_time.split(" ")[1]
            if time in yester_time:
                for device in device_level_mapping_values:
                    yester_total += float(yester_file_content["device"][date_time][str(device)])            

        current_total = float(current_file_content['total']['levels']['level'+str(level)][str(l_id)])
        baseline_energy_yester = (yester_total) - current_total
        results = (current_total,baseline_energy_yester)
        print results # prints(123,345) but does not returns. instead goes into except for week,month and year and returns (123,Nan)
        return results

    except: 

        current_total = float(current_file_content['total']['levels']['level'+str(level)][str(l_id)])
        baseline_energy_yester = "NaN"
        results = (current_total,baseline_energy_yester)
        return results
4

2 回答 2

1

except在不识别您正在捕获的类型的情况下使用是一种危险的反模式。如果try块中的代码遇到KeyboardInterrupt,或NameError,假设继续安全并且恢复只是确保 ' ' 为空是否真的安全?ImportErrorIOErrorsearch_name

try : search_name = request.POST['search_name']
except : search_name = ""

顺便说一句,如果没有定义匹配的键,您可以要求 adict返回默认值:

search_name = request.POST.get('search_name', None)

相反,它进入 except 块并返回其他内容。

通常,如果您的代码遇到异常,则说明有些“错误”。错误可能会有所不同,因此它可能不会造成破坏,但如果您不确定发生了哪个异常以及为什么发生,那么最好不要尝试处理它。让它在堆栈中一路向上飞到一些具有要恢复的上下文或优雅失败的代码,或者在这种情况下更好 - 一直到开发人员(你!),这样你就可以解决设计中的失败/执行。

于 2013-11-08T04:56:52.040 回答
0

要获取 POST 发布数据字段的值,请尝试使用

period_val = request.POST.get('period_val')

代替

period_val = request.POST['period_val']
于 2013-11-08T04:49:16.083 回答