111.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from fastapi import FastAPI, HTTPException
  2. from pydantic import BaseModel
  3. import dmPython
  4. from typing import List, Dict
  5. app = FastAPI()
  6. class TableRequest(BaseModel):
  7. table: str
  8. def get_column_comments(cursor, schema: str, table: str) -> Dict[str, str]:
  9. """
  10. 获取指定表中所有字段的备注信息。
  11. """
  12. query = f"""
  13. SELECT aa.COLUMN_NAME, ss.comments AS 描述
  14. FROM user_tab_columns aa
  15. INNER JOIN user_col_comments ss
  16. ON ss.COLUMN_NAME = aa.COLUMN_NAME
  17. AND ss.Table_Name = aa.Table_Name
  18. WHERE aa.Table_Name = '{table}'
  19. ORDER BY aa.column_id
  20. """
  21. cursor.execute(query)
  22. return {row[0]: row[1] if row[1] else row[0] for row in cursor.fetchall()}
  23. @app.post("/fetch_table_data")
  24. async def fetch_table_data(request: TableRequest):
  25. result_list = []
  26. try:
  27. conn = dmPython.connect(user="SYSDBA", password="SYSDBA123", server="192.168.100.102", port=5236, schema='lqbz')
  28. cursor = conn.cursor()
  29. try:
  30. # 获取字段备注信息
  31. column_comments = get_column_comments(cursor, schema='lqbz', table=request.table)
  32. # 执行查询
  33. cursor.execute(f"select * from {request.table}")
  34. # 获取列名
  35. column_names = [description[0] for description in cursor.description]
  36. # 获取所有数据
  37. rows = cursor.fetchall()
  38. # 将每一行数据与列名组合成字典,并使用备注信息作为键
  39. result_dicts = [
  40. {column_comments.get(column_name, column_name): value for column_name, value in zip(column_names, row)} for
  41. row in rows]
  42. return {"data": result_dicts}
  43. except (dmPython.Error, Exception) as err:
  44. raise HTTPException(status_code=500, detail=f"发生错误: {err}")
  45. finally:
  46. cursor.close()
  47. except (dmPython.Error, Exception) as err:
  48. raise HTTPException(status_code=500, detail=f"发生错误: {err}")
  49. finally:
  50. if 'conn' in locals():
  51. conn.close()
  52. if __name__ == "__main__":
  53. import uvicorn
  54. uvicorn.run(app, host="0.0.0.0", port=7077)