为什么我的API响应总是无效的?我的call_api函数有问题吗?[已解决]

huangapple go评论137阅读模式
英文:

Why are my API response always invalid ? Is there something wrong with my call_api function?[Solved]

问题

在我的call_api函数中,我使用了一种不同的方法来检测无效/有效的API,即通过检查响应头"Response_Description"中是否存在字符串"Hazard was successfully processed and at least one value is returned."。不知何故,我的输出始终为false,标记为输出表中的Pass列中的N。

  1. def call_api(url):
  2. try:
  3. headers = {
  4. "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"
  5. }
  6. response = requests.get(url, headers=headers)
  7. json_response = response.json()
  8. if (
  9. "Response_Description" in json_response
  10. and "Hazard was successfully processed" in json_response["Response_Description"]
  11. ):
  12. return True
  13. else:
  14. return False
  15. except requests.exceptions.RequestException:
  16. return False
  17. # 其余的代码部分保持不变

如果你希望在修改代码后正确验证API,请确保API的响应中包含所需的字符串 "Hazard was successfully processed",并且这个字符串在 "Response_Description" 中出现。如果API响应的格式或内容发生变化,你可能需要相应地调整代码以匹配新的响应格式。

英文:

In my call_api function, I used a different way to detect invalid/valid APIs which was by checking if the string, "Hazard was successfully processed and at least one value is returned." was present in the header "Response_Description". Somehow my output is always false which is labelled N in the output table under the Pass column.

  1. def call_api(url):
  2. try:
  3. headers = {
  4. "User-Agent": "Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36"
  5. }
  6. response = requests.get(url, headers=headers)
  7. json_response = response.json()
  8. if (
  9. "Response_Description" in json_response
  10. and "Hazard was successfully processed" in json_response["Response_Description"]
  11. ):
  12. return True
  13. else:
  14. return False
  15. except requests.exceptions.RequestException:
  16. return False
  17. df = pd.read_csv(r"C:\Users\Jose.Moquaimbo\Bulk Calling APIs\dataset.csv")
  18. # Number of iterations
  19. num_iterations = 5
  20. # Create an empty DataFrame to store the results
  21. results_df = pd.DataFrame(columns=["Iteration", "Pass", "Time Taken"])
  22. # Variables for tracking min, max, and total time
  23. min_time = float("inf")
  24. max_time = float("-inf")
  25. total_time = 0
  26. def process_iteration(iteration):
  27. # Get a random sample of URLs from the DataFrame
  28. random_urls = df["url"].sample(n=1).tolist()
  29. # Execute API calls concurrently using ThreadPoolExecutor
  30. with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
  31. start_time = time.time()
  32. futures = [executor.submit(call_api, url) for url in random_urls]
  33. # Wait for all futures to complete and get their results
  34. results = [future.result() for future in futures]
  35. # Stop timer
  36. end_time = time.time()
  37. # Calculate the time taken for this iteration
  38. iteration_time = end_time - start_time
  39. # Update min, max, and total time
  40. global min_time, max_time, total_time
  41. min_time = min(min_time, iteration_time)
  42. max_time = max(max_time, iteration_time)
  43. total_time += iteration_time
  44. # Check if any API call was not successful in this iteration
  45. passed = "Y" if all(results) else "N"
  46. # Add the iteration results to the DataFrame
  47. results_df.loc[iteration] = [iteration, passed, iteration_time]
  48. # Run the iterations
  49. for i in range(1, num_iterations + 1):
  50. process_iteration(i)
  51. # Calculate average time per iteration
  52. avg_time = total_time / num_iterations
  53. # Display the results DataFrame
  54. print(results_df)
  55. # Summary statistics
  56. print("Minimum time taken:", min_time)
  57. print("Maximum time taken:", max_time)
  58. print("Average time per iteration:", avg_time)
  59. print("Y stands for error-free response and N for invalid response")

Output

  1. Iteration Pass Time Taken
  2. 1 1 N 0.276398
  3. 2 2 N 0.298180
  4. 3 3 N 0.307337
  5. 4 4 N 0.323730
  6. 5 5 N 0.333215
  7. Minimum time taken: 0.2763981819152832
  8. Maximum time taken: 0.33321452140808105
  9. Average time per iteration: 0.3077719688415527
  10. Y stands for error-free response and N for invalid response

Is there a way to modify the code, so it can correctly validate the API because it seems that the API is always invalidated. I suspect something is wrong my call_api function

Edit:

  1. response_text = response.text

答案1

得分: 1

重构你的call_api()函数,以更好地处理异常并报告可能出现的问题。

  1. import requests
  2. import sys
  3. HEADERS = {
  4. 'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36'
  5. }
  6. KEY = 'Response_Description'
  7. VALUE = 'Hazard was successfully processed'
  8. def call_api(url: str) -> bool:
  9. try:
  10. with requests.get(url, headers=HEADERS) as response:
  11. response.raise_for_status()
  12. return VALUE in response.json().get(KEY, '')
  13. except Exception as e:
  14. print(e, file=sys.stderr)
  15. return False
英文:

Restructure your call_api() function to better handle exceptions and report any problems that might arise.

  1. import requests
  2. import sys
  3. HEADERS = {
  4. 'User-Agent': 'Mozilla/5.0 (X11; CrOS x86_64 12871.102.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36'
  5. }
  6. KEY = 'Response_Description'
  7. VALUE = 'Hazard was successfully processed'
  8. def call_api(url: str) -> bool:
  9. try:
  10. with requests.get(url, headers=HEADERS) as response:
  11. response.raise_for_status()
  12. return VALUE in response.json().get(KEY, '')
  13. except Exception as e:
  14. print(e, file=sys.stderr)
  15. return False

huangapple
  • 本文由 发表于 2023年6月15日 14:51:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定