Python不返回变量

时间:2013-11-08 04:29:25

标签: python

我试图在python中返回变量(列表),但它不允许我返回它。相反,它进入除了阻止并返回其他东西。

代码是这样的:最初我通过Ajax调用获得period_value(datetime)search_name(location name)time_period(day,week,month,year)。如果它的日期,那么它的工作正常,但在其他情况下(周,月,年)结果变量确实给我满意的数据,但它不返回数据,而是进入除了并返回其他东西。这似乎是一个奇怪的问题。请检查我出错的地方?

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函数

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

2 个答案:

答案 0 :(得分:1)

使用except而不识别您正在捕捉的类型是一种危险的反模式。如果try块中的代码遇到KeyboardInterruptNameErrorImportErrorIOError,那么假设继续安全并且恢复只是为了确保'search_name'为空?

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

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

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

  

相反,它进入除了阻止并返回其他东西。

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

答案 1 :(得分:0)

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

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

而不是

period_val = request.POST['period_val']