api_20241201.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # coding=utf-8
  2. from fastapi import FastAPI, UploadFile, HTTPException
  3. from fastapi.responses import JSONResponse
  4. from typing import List, Optional
  5. from pydantic import BaseModel
  6. import os
  7. import json
  8. import shutil
  9. import pandas as pd
  10. import uvicorn
  11. from cms_class_20241201 import CMSAnalyst
  12. from typing import List, Optional, Union
  13. from pydantic import BaseModel, Field, model_validator
  14. # 初始化 FastAPI 应用
  15. app = FastAPI()
  16. '''
  17. input:
  18. {
  19. "ids":[12345,121212],
  20. "windCode":"xxxx",
  21. "analysisType":"xxxxx",
  22. "fmin":int(xxxx) (None),
  23. "fmax":"int(xxxx) (None),
  24. }
  25. output:
  26. {
  27. data:[
  28. {
  29. "type":"envelope_spectrum",
  30. "x":list(x),
  31. "y":list(y),
  32. "title":title,
  33. "xaxis":xaxis,
  34. "yaxis":yaxis
  35. },
  36. {
  37. "type":"bandpass_filtered",
  38. "x":list(x),
  39. "y":list(y),
  40. "title":title,
  41. "xaxis":xaxis,
  42. "yaxis":yaxis
  43. },
  44. # 其他情况:
  45. {
  46. "type":"trend_analysis",
  47. "Mean": mean_value,
  48. "Max": max_value,
  49. "Min": min_value,
  50. "Xrms": Xrms,
  51. "Xp": Xp,
  52. "If": If,
  53. "Cf": Cf,
  54. "Sf": Sf,
  55. "Ce": Ce,
  56. "Cw": Cw,
  57. "Cq": Cq
  58. }
  59. ],
  60. "code": 200,
  61. "message":success
  62. }
  63. '''
  64. # 请求模型定义
  65. class AnalysisInput(BaseModel):
  66. # ids: List
  67. ids: List[int]
  68. windCode: str
  69. analysisType: str
  70. fmin: Optional[int] = None
  71. fmax: Optional[int] = None
  72. @model_validator(mode='before')
  73. def convert_ids(cls, values):
  74. if isinstance(values.get('ids'), int):
  75. values['ids'] = [values['ids']]
  76. return values
  77. # url = "http://127.0.0.1:8888/analysis/trend"
  78. @app.post("/analysis/{analysisType}")
  79. async def analyze(analysisType: str, input_data:AnalysisInput):
  80. analysis_map = {
  81. "envelope": "envelope_spectrum",#包络谱分析
  82. "frequency": "frequency_domain",#频域分析
  83. "time": "time_domain",#时域分析
  84. "trend": "trend_analysis"#趋势分析
  85. }
  86. if analysisType not in analysis_map:
  87. raise HTTPException(status_code=400, detail="非可用的分析类型")
  88. try:
  89. cms = CMSAnalyst(input_data.fmin, input_data.fmax, input_data.windCode, input_data.ids)
  90. func = getattr(cms, analysis_map[analysisType])
  91. # if callable(func):
  92. # func_res = func()
  93. # func_res = json.loads(func_res)
  94. # func_res['type'] = analysisType
  95. # # return {
  96. # # "message": "success",
  97. # # "data": [func_res],
  98. # # }
  99. if callable(func): # 用于判断一个对象是否可以被调用,是的话返回true
  100. func_res = func()
  101. if isinstance(func_res, str):
  102. func_res = json.loads(func_res) # 字符串转化为字典形式
  103. if isinstance(func_res, dict):
  104. func_res['type'] = analysisType
  105. elif isinstance(func_res, list):
  106. func_res = {'type': analysisType, 'data': func_res}
  107. else:
  108. # 处理其他情况,例如其他数据类型
  109. func_res = {'type': analysisType, 'data': str(func_res)}
  110. return json.dumps(func_res,ensure_ascii=False) #对象转化为字符串形式
  111. # return JSONResponse(content=func_res)#返回json格式
  112. except Exception as e:
  113. return {"message": "error", "detail": str(e)}
  114. # @app.post("/analysis/{analysisType}")
  115. # async def analyze(analysisType: str, input_data:AnalysisInput):
  116. # try:
  117. # analysis_map = {
  118. # "envelope": ["envelope_spectrum","bandpass_filtered"],
  119. # "frequency": "frequency_domain",
  120. # "time": "time_domain",
  121. # "trend": "trend_analysis"
  122. # }
  123. # if analysisType not in analysis_map:
  124. # raise HTTPException(status_code=400, detail="非可用的分析类型")
  125. # try:
  126. # cms = CMSAnalyst(input_data.fmin, input_data.fmax, input_data.windCode, input_data.ids)
  127. # if analysisType == "envelope":
  128. # tmp = []
  129. # for type_func in analysis_map[analysisType]:
  130. # func = getattr(cms, type_func)
  131. # if callable(func):
  132. # func_res = func()
  133. # func_res['type'] = analysisType
  134. # tmp.append(func_res)
  135. # return {
  136. # "message": "success",
  137. # "data": tmp,
  138. # }
  139. # else:
  140. # func = getattr(cms, analysis_map[analysisType])
  141. # if callable(func):
  142. # func_res = func()
  143. # func_res['type'] = analysisType
  144. # return {
  145. # "message": "success",
  146. # "data": [func_res],
  147. # }
  148. # except Exception as e:
  149. # return {"message": "error", "detail": str(e)}
  150. # except:
  151. # raise HTTPException(status_code=400, detail="接口返回错误")
  152. if __name__ == "__main__":
  153. uvicorn.run(
  154. app,
  155. host=("0.0.0.0"),
  156. port=8888
  157. )