我正在使用Django-rest-framework开发API。请求在get()
中,用户输入一个日期和部门编号,并获得响应,其中包含有关该特定部门的特定日期的销售指标。
问题:问题在于,在某些情况下,对于2018年的旧数据,我正在查询的大多数字段都是零,并且有一个分区可以计算一些指标,因此您最终可以通过获得NAN,而这些api的功能都破坏了API的功能。
这是我的视图中的示例代码:
sql = "select sales_p, sales_c, sales_all from sales where dat_ref = '" + input_date + "'"
try:
df = select_vector(sql, DB_CONNECTOR)
except Exception:
raise ServiceUnavailable()
if df is None:
raise ServiceUnavailable()
if len(df) > 0:
sales_1 = df['sales_p'].loc[0]
sales_2 = df5['sales_c'].loc[0]
sales_all = df5['sales_all'].loc[0]
else:
return Response(status=204)
percentage = float(("{0:.2f}".format(((sales_all - sales_p)/sales_c)*100)))
response = {'Percentage': percentage}
我正在寻找处理此问题的最佳方法,并可能将消息返回给用户澄清。
最简单的解决方案可能只是要放置:
if sales_c == 0:
#Handle the error however you want, raise an exception print a message or whatever else
else:
#Continue with program
请让我知道,如果这没有出于某种原因而没有解决问题,我可能错过了问题声明中的一些东西。