base_from_python.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. package services
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "eta_gn/eta_index_lib/models"
  6. "eta_gn/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/shopspring/decimal"
  9. "os"
  10. "os/exec"
  11. "reflect"
  12. "strings"
  13. )
  14. // EdbDataStrFromPython 通过python代码获取到的指标数据(interface数据)
  15. type EdbDataStrFromPython struct {
  16. Date map[int]string `json:"date"`
  17. Value map[int]interface{} `json:"value"`
  18. }
  19. // ExecPythonCode 执行Python代码
  20. func ExecPythonCode(edbCode, reqCode string) (dataMap models.EdbDataFromPython, err error, errMsg string) {
  21. defer func() {
  22. if err != nil {
  23. fmt.Println("err:", err)
  24. }
  25. }()
  26. codeStr := strings.ToLower(reqCode)
  27. // 限制python代码的执行,如果包含特殊的关键词,则报错
  28. if strings.Contains(codeStr, "drop table") || strings.Contains(codeStr, "delete") || strings.Contains(codeStr, "update") || strings.Contains(codeStr, "alter") || strings.Contains(codeStr, "truncate") {
  29. err = fmt.Errorf("不支持该命令")
  30. return
  31. }
  32. //获取python文件的绝对地址
  33. pythonFile, err := getPythonFileAbsolutePath(edbCode)
  34. if err != nil {
  35. return
  36. }
  37. pythonCodeStr := getPythonFrontStr() + reqCode + getPythonLaterStr()
  38. fileHandle, err := os.OpenFile(pythonFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0766)
  39. if err != nil {
  40. return
  41. }
  42. defer func() {
  43. os.Remove(pythonFile)
  44. }()
  45. _, err = fileHandle.Write([]byte(pythonCodeStr))
  46. if err != nil {
  47. return
  48. }
  49. fileHandle.Close()
  50. cmd := exec.Command(utils.PYTHON_PATH, pythonFile)
  51. var out, errMsgOut bytes.Buffer
  52. cmd.Stdout = &out
  53. cmd.Stderr = &errMsgOut
  54. err = cmd.Run()
  55. if err != nil {
  56. errMsg = errMsgOut.String()
  57. return
  58. }
  59. outputByte := out.String()
  60. if err != nil {
  61. return
  62. }
  63. //fmt.Println(string(outputByte))
  64. arr := strings.Split(string(outputByte), "result=")
  65. arrLen := len(arr)
  66. //fmt.Println(arr)
  67. if arrLen <= 1 {
  68. err = fmt.Errorf("python运算结果异常")
  69. return
  70. }
  71. resultStr := arr[arrLen-1]
  72. //fmt.Println(resultStr)
  73. var dataMapStr EdbDataStrFromPython
  74. //先将value转为interface
  75. err = json.Unmarshal([]byte(resultStr), &dataMapStr)
  76. if err != nil {
  77. return
  78. }
  79. dataMap.Date = make(map[int]string)
  80. dataMap.Value = make(map[int]float64)
  81. //将value为nil的给过滤掉
  82. i := 0
  83. lenData := len(dataMapStr.Date)
  84. for k := 0; k < lenData; k++ {
  85. date := dataMapStr.Date[k]
  86. tmpValue := dataMapStr.Value[k]
  87. if reflect.TypeOf(tmpValue) != nil {
  88. if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
  89. dataMap.Date[i] = date
  90. dataMap.Value[i], _ = decimal.NewFromFloat(reflect.ValueOf(tmpValue).Float()).Truncate(4).Float64() //保留4位小数
  91. i++
  92. }
  93. }
  94. }
  95. //err = json.Unmarshal([]byte(resultStr), &dataMap)
  96. //fmt.Println(dataMap)
  97. return
  98. }
  99. // getPythonFileAbsolutePath 获取python文件的绝对地址
  100. func getPythonFileAbsolutePath(edbCode string) (pythonFile string, err error) {
  101. uploadDir := utils.STATIC_DIR + "python/"
  102. err = os.MkdirAll(uploadDir, 0766)
  103. if err != nil {
  104. return
  105. }
  106. pythonFile = uploadDir + fmt.Sprint(edbCode, "_", utils.GetRandDigit(16), ".py")
  107. if utils.RunMode != "release" {
  108. dir, tmpErr := os.Getwd()
  109. if tmpErr != nil {
  110. err = tmpErr
  111. return
  112. }
  113. pythonFile = dir + "/" + pythonFile
  114. }
  115. return
  116. }
  117. // getPythonFrontStr 获取python前面的代码
  118. func getPythonFrontStr() string {
  119. //return "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport pymysql\nimport pandas as pd\n\nsql_config = {\n 'host': 'rm-uf67kg347rhjfep5c1o.mysql.rds.aliyuncs.com',\n 'port': 3306,#主机号\n 'user': 'hz_technology',#账户名\n 'passwd': 'hongze@2021',#密码\n 'db': 'test_hz_data',\n 'charset': 'utf8mb4',\n 'cursorclass': pymysql.cursors.DictCursor\n}\n\ndb = pymysql.connect(**sql_config)\ndb.autocommit(1)\ncursor = db.cursor()\npandas_fetch_all = pd.read_sql\n\n# 返回数据\nresult = {}\n\n# 格式化返回数据\ndef format_data(data: pd.DataFrame,\n index_str: str = \"data_time\",\n value_str: str = \"value\"\n ) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n data : pandas的DataFrame数据结构.\n index_str : 对象下标字符串,在pandas的DataFrame中的列名.\n value_str : 对象值字符串,在pandas的DataFrame中的列名\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n 例子:{'2007-01-09': 3220.0, '2007-01-10': 3230.0}\n\n \"\"\"\n index_list = [] # 空列表\n value_list = [] # 空列表\n\n for num in range(1, data.index.size): # 迭代 所有的指标\n index_list.append(data[index_str][num])\n value_list.append(data[value_str][num])\n\n tmp_data = {\n \"date\": index_list,\n \"value\": value_list\n }\n pd_data = pd.DataFrame(tmp_data)\n # print(pd_data)\n return pd_data\n"
  120. str := fmt.Sprintf("#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport dmPython\nimport pandas as pd\nfrom pymongo import MongoClient\nimport pytz\n\nproperties = %s\n\ndb = dmPython.connect(**properties)\ncursor = db.cursor()\npandas_fetch_all = pd.read_sql\n\n", utils.PYTHON_DM_CONNECT_PARAM)
  121. // mongo部分
  122. if utils.PYTHON_MONGO_HOST != `` {
  123. str += getPythonFront2Str()
  124. }
  125. // 格式化数据部分
  126. str += getPythonFront3Str()
  127. return str
  128. }
  129. // getPythonFront2Str
  130. // @Description: mongo部分
  131. // @author: Roc
  132. // @datetime 2024-05-07 18:38:03
  133. // @return string
  134. func getPythonFront2Str() string {
  135. str := fmt.Sprintf("\nfrom pymongo import MongoClient\nfrom dateutil.tz import tzlocal\n# MongoDB 连接配置\nmongo_config = {\n 'host': '%s', # 替换为你的 MongoDB 连接字符串\n 'database': '%s', # 替换为你的数据库名\n 'collection': '%s', # 替换为你的集合名\n 'auth_mechanism': '%s' # 替换为你的认证机制\n}\n\n# 创建 MongoClient 并连接到数据库\nclient = MongoClient(mongo_config['host'], authMechanism=mongo_config['auth_mechanism'])\nmgo_db = client[mongo_config['database']]\ncollection = mgo_db[mongo_config['collection']]\n\n# 定义时区\nutc_tz = pytz.utc\nlocal_tz = tzlocal() # 本地时区", utils.PYTHON_MONGO_HOST, utils.PYTHON_MONGO_DATABASE, "edb_data_business", utils.PYTHON_MONGO_AUTH_MECHANISM)
  136. return str
  137. }
  138. // getPythonFront3Str
  139. // @Description: 第三部分
  140. // @author: Roc
  141. // @datetime 2024-05-07 18:37:56
  142. // @return string
  143. func getPythonFront3Str() string {
  144. str := fmt.Sprintf("\n# 返回数据\nresult = {}\n\n# 格式化返回数据\ndef format_data(data: pd.DataFrame,\n index_str: str = \"data_time\",\n value_str: str = \"value\"\n ) -> pd.DataFrame:\n \"\"\"\n Parameters\n ----------\n data : pandas的DataFrame数据结构.\n index_str : 对象下标字符串,在pandas的DataFrame中的列名.\n value_str : 对象值字符串,在pandas的DataFrame中的列名\n\n Returns\n -------\n DataFrame or Iterator[DataFrame]\n 例子:{'2007-01-09': 3220.0, '2007-01-10': 3230.0}\n\n \"\"\"\n index_list = [] # 空列表\n value_list = [] # 空列表\n\n for num in range(0, data.index.size): # 迭代 所有的指标\n date=data[index_str][num]\n if isinstance(date,str) is False:\n index_list.append(data[index_str][num].strftime(\"%%Y-%%m-%%d\"))\n else:\n index_list.append(data[index_str][num])\n value_list.append(data[value_str][num])\n\n tmp_data = {\n \"date\": index_list,\n \"value\": value_list\n }\n pd_data = pd.DataFrame(tmp_data)\n return pd_data\n\n")
  145. return str
  146. }
  147. // getPythonLaterStr 获取python结尾的代码
  148. func getPythonLaterStr() string {
  149. return "\n\nprint(\"result=\", result.to_json())\ndb.close()"
  150. }