對於開發功能,除了把功能實現之外,對於有輸入的功能要能夠具備有處理使用者任何輸入的狀況
舉例來說
實現一個計算的功能,今天如果有除法這個計算功能
是否就得考慮使用者輸入除以零這個數字
在以前來說除0是不合法的,因為compoler不會過
不過IEEE 754 二進位浮點數算術標準
https://zh.wikipedia.org/zh-tw/IEEE_754
其實有定義了inf 與 -inf
所以 除0為 inf, log(0)為 -inf 就為合理的結果
除此之外 除法還有一個需要考慮的輸出結果位數
1/3 = 0.33333333…
今天假設 1/3 = 0.33當結果
會不會造成 1/3 + 1/3 + 1/3 = 0.99
這些都是防呆機制所需要考慮的
以下是一些防呆機制範例
df = pd.DataFrame()
tag = True
# Retry up to three times
for _ in range(3):
response = requests.get("http://172.22.83.191/Abnormal_API/api/GetAll")
if response.status_code == 200:
data = response.json()
df = pd.DataFrame(data)
# Check if "登錄時間" column exists and is not 'null'
if "登錄時間" in df.columns and not df["登錄時間"].eq('null').any():
break # Break the loop if conditions are met
else:
# Wait for some time before retrying
time.sleep(1)
else:
tag = False
# If loop completes without breaking, raise an exception
這個是調用api使用最多三次的retry的防呆機制
#filter the machine model
df = df[df['機種'].str.contains(info.machine_model)]
# filter the problem type
## remove special character
problem_type = str(info.problem_type)
problem_type = "".join(ch for ch in problem_type if ch.isalnum())
df['異常類型明細名稱'] = df['異常類型明細名稱'].str.replace(r'\W', '', regex=True)
# df['異常類型附件'] = df['異常類型附件'].str.replace(r'\W', '', regex=True)
## all lowercase
problem_type = problem_type.lower()
df['異常類型明細名稱'] = df['異常類型明細名稱'].str.lower()
# ## remove space
problem_type = "".join(ch for ch in problem_type if ch!="")
df['異常類型明細名稱'] = df['異常類型明細名稱'].apply(lambda x: x.replace(' ', ''))
df = df[df['異常類型明細名稱'].str.contains(problem_type)]
if df.empty:
return f"There are no data of {info.problem_type} for machine model {info.machine_model}.", info.language
這個是對於dataframe欄位選擇後如果為空就直接return的防呆機制
if (np.any(unique_wo != "")) or (np.any(unique_site != "")) or (np.any(unique_person != "")):
return f"There are {len(df)} occurance of {info.problem_type} for machine model {machine} \n\n工單: {unique_wo} \n\n站點: {unique_site} \n\n異常登陸人員: {unique_person} \n\n 日期: {unique_date} \n\n Issue Type :{info.problem_type} \n\n Error Type :{unique_type}:{cleaned_unique_append}\n\n 1. {info.problem_type}{out1}\n\n 2. {ans2} \n\n 3. {ans1}", info.language
else:
return f"There are no data of {info.problem_type} for machine model {info.machine_model}.", info.language
else:
return f"Cannot call the API or retrieve valid data in {info.machine_model}", info.language
這邊是對於df細項如果為空的防呆機制。
有沒有所謂的最好最完美的防呆機制? {try except} ?