base_from_python.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package services
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "eta/eta_index_lib/models"
  6. "eta/eta_index_lib/utils"
  7. "fmt"
  8. "github.com/shopspring/decimal"
  9. "os"
  10. "os/exec"
  11. "reflect"
  12. "regexp"
  13. "strconv"
  14. "strings"
  15. )
  16. func Test() (err error) {
  17. defer func() {
  18. if err != nil {
  19. fmt.Println("err:", err)
  20. }
  21. }()
  22. ///usr/local/bin/python3.9
  23. //exec.Command("bin/bash", "-c")
  24. //cmd := exec.Command("/usr/local/bin/python3.9", "-c", "/Users/roc/go/src/eta/eta_index_lib/test2.py")
  25. //cmd := exec.Command("python3", "-c", "./test2.py")
  26. cmd := exec.Command("python3", "/Users/roc/go/src/eta/eta_index_lib/test2.py")
  27. outputByte, err := cmd.Output()
  28. //fmt.Println(err)
  29. fmt.Println("start")
  30. if err != nil {
  31. return
  32. }
  33. fmt.Println(string(outputByte))
  34. arr := strings.Split(string(outputByte), "result=")
  35. arrLen := len(arr)
  36. //fmt.Println(arr)
  37. if arrLen <= 1 {
  38. err = fmt.Errorf("python运算结果异常")
  39. return
  40. }
  41. resultStr := arr[arrLen-1]
  42. fmt.Println(resultStr)
  43. var dataMap map[string]float64
  44. json.Unmarshal([]byte(resultStr), &dataMap)
  45. fmt.Println(dataMap)
  46. //i, err := python3.Py_Main(os.Args)
  47. //if err != nil {
  48. // fmt.Printf("error launching the python interpreter: %s\n", err)
  49. // os.Exit(1)
  50. //}
  51. ////commStr := "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport pymysql\nimport pandas as pd\nfrom test_bak import sql_config\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 ) -> dict:\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 tmp_result = {}\n for num in range(1, data.index.size): # 迭代 所有的指标\n tmp_result[data[index_str][num]] = data[value_str][num]\n return tmp_result\n\n\ndef query():\n edb_code = 's0033227'\n data_time = '2002-03-17'\n # field_name = '平均温度'\n sql1 = f\"\"\"SELECT data_time,`value` FROM edb_data_wind WHERE edb_code = '{edb_code}' and data_time > '{data_time}' ;\"\"\"\n raw = pandas_fetch_all(sql1, db)\n raw['data_time_str'] = raw['data_time'].apply(lambda x: x.strftime(\"%Y-%m-%d\"))\n format_result = format_data(raw, \"data_time_str\", \"value\")\n print(format_result)\n return format_result\n\n\nresult = query()\ndb.close()\n"
  52. ////i := python3.PyRun_SimpleString(commStr)
  53. //fmt.Println(i)
  54. return
  55. }
  56. // EdbDataStrFromPython 通过python代码获取到的指标数据(interface数据)
  57. type EdbDataStrFromPython struct {
  58. Date map[int]string `json:"date"`
  59. Value map[int]interface{} `json:"value"`
  60. }
  61. // ExecPythonCode 执行Python代码
  62. func ExecPythonCode(edbCode, reqCode string) (dataMap models.EdbDataFromPython, err error, errMsg string) {
  63. defer func() {
  64. if err != nil {
  65. fmt.Println("err:", err)
  66. }
  67. }()
  68. codeStr := strings.ToLower(reqCode)
  69. // 限制python代码的执行,如果包含特殊的关键词,则报错
  70. if strings.Contains(codeStr, "drop table") || strings.Contains(codeStr, "delete") || strings.Contains(codeStr, "update") || strings.Contains(codeStr, "alter") || strings.Contains(codeStr, "truncate") {
  71. err = fmt.Errorf("不支持该命令")
  72. return
  73. }
  74. //获取python文件的绝对地址
  75. pythonFile, err := getPythonFileAbsolutePath(edbCode)
  76. if err != nil {
  77. return
  78. }
  79. pythonCodeStr := getPythonFrontStr() + reqCode + getPythonLaterStr()
  80. fileHandle, err := os.OpenFile(pythonFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0766)
  81. if err != nil {
  82. return
  83. }
  84. // 获取指定头部的换行符数量
  85. frontNumN := getPythonFrontNumN()
  86. defer func() {
  87. os.Remove(pythonFile)
  88. }()
  89. _, err = fileHandle.Write([]byte(pythonCodeStr))
  90. if err != nil {
  91. return
  92. }
  93. fileHandle.Close()
  94. cmd := exec.Command(utils.PYTHON_PATH, pythonFile)
  95. var out, errMsgOut bytes.Buffer
  96. cmd.Stdout = &out
  97. cmd.Stderr = &errMsgOut
  98. err = cmd.Run()
  99. if err != nil {
  100. errMsg = errMsgOut.String()
  101. // 替换Python文件名
  102. errMsg = strings.Replace(errMsgOut.String(), pythonFile, "python file", -1)
  103. tmpErrMsg, tmpErr := replaceLineNumber(errMsg, frontNumN)
  104. if tmpErr == nil {
  105. errMsg = tmpErrMsg
  106. }
  107. return
  108. }
  109. outputByte := out.String()
  110. if err != nil {
  111. return
  112. }
  113. //fmt.Println(string(outputByte))
  114. arr := strings.Split(string(outputByte), "result=")
  115. arrLen := len(arr)
  116. //fmt.Println(arr)
  117. if arrLen <= 1 {
  118. err = fmt.Errorf("python运算结果异常")
  119. return
  120. }
  121. resultStr := arr[arrLen-1]
  122. //fmt.Println(resultStr)
  123. var dataMapStr EdbDataStrFromPython
  124. //先将value转为interface
  125. err = json.Unmarshal([]byte(resultStr), &dataMapStr)
  126. if err != nil {
  127. return
  128. }
  129. dataMap.Date = make(map[int]string)
  130. dataMap.Value = make(map[int]float64)
  131. //将value为nil的给过滤掉
  132. i := 0
  133. lenData := len(dataMapStr.Date)
  134. for k := 0; k < lenData; k++ {
  135. date := dataMapStr.Date[k]
  136. tmpValue := dataMapStr.Value[k]
  137. if reflect.TypeOf(tmpValue) != nil {
  138. if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
  139. dataMap.Date[i] = date
  140. dataMap.Value[i], _ = decimal.NewFromFloat(reflect.ValueOf(tmpValue).Float()).Truncate(4).Float64() //保留4位小数
  141. i++
  142. }
  143. }
  144. }
  145. //err = json.Unmarshal([]byte(resultStr), &dataMap)
  146. //fmt.Println(dataMap)
  147. return
  148. }
  149. // getPythonFileAbsolutePath 获取python文件的绝对地址
  150. func getPythonFileAbsolutePath(edbCode string) (pythonFile string, err error) {
  151. uploadDir := utils.STATIC_DIR + "python/"
  152. err = os.MkdirAll(uploadDir, 0766)
  153. if err != nil {
  154. return
  155. }
  156. pythonFile = uploadDir + fmt.Sprint(edbCode, "_", utils.GetRandDigit(16), ".py")
  157. if utils.RunMode != "release" {
  158. dir, tmpErr := os.Getwd()
  159. if tmpErr != nil {
  160. err = tmpErr
  161. return
  162. }
  163. pythonFile = dir + "/" + pythonFile
  164. }
  165. return
  166. }
  167. // getPythonFrontStr 获取python前面的代码
  168. func getPythonFrontStr() string {
  169. //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"
  170. str := fmt.Sprintf("#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport pymysql\nimport pandas as pd\nfrom pymongo import MongoClient\nimport pytz\n\nsql_config = {\n 'host': '%s',\n 'port': 3306,#主机号\n 'user': '%s',#账户名\n 'passwd': '%s',#密码\n 'db': '%s',\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", utils.PYTHON_MYSQL_HOST, utils.PYTHON_MYSQL_USER, utils.PYTHON_MYSQL_PASSWD, utils.PYTHON_MYSQL_DB)
  171. // mongo部分
  172. if utils.PYTHON_MONGO_HOST != `` {
  173. str += getPythonFront2Str()
  174. }
  175. // 格式化数据部分
  176. str += getPythonFront3Str()
  177. return str
  178. }
  179. // getPythonFront2Str
  180. // @Description: mongo部分
  181. // @author: Roc
  182. // @datetime 2024-05-07 18:38:03
  183. // @return string
  184. func getPythonFront2Str() string {
  185. 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}\n\n# 创建 MongoClient 并连接到数据库\nclient = MongoClient(mongo_config['host'])\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")
  186. return str
  187. }
  188. // getPythonFront3Str
  189. // @Description: 第三部分
  190. // @author: Roc
  191. // @datetime 2024-05-07 18:37:56
  192. // @return string
  193. func getPythonFront3Str() string {
  194. 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")
  195. return str
  196. }
  197. // getPythonLaterStr 获取python结尾的代码
  198. func getPythonLaterStr() string {
  199. return "\n\nprint(\"result=\", result.to_json())\ndb.close()"
  200. }
  201. // getPythonFrontNumN
  202. // @Description: 获取指定头部的换行符数量
  203. // @author: Roc
  204. // @datetime 2024-05-08 10:15:51
  205. // @return int
  206. func getPythonFrontNumN() int {
  207. re := regexp.MustCompile("\n")
  208. matches := re.FindAllStringIndex(getPythonFrontStr(), -1)
  209. return len(matches) // 每个匹配的结果对应一个换行符
  210. }
  211. func replaceLineNumber(errorText string, frontNumber int) (string, error) {
  212. // 编译正则表达式,匹配 "line" 后面跟一个或多个空格,再跟一个或多个数字的模式
  213. re := regexp.MustCompile(`line\s+\d+`)
  214. match := re.FindStringSubmatch(errorText)
  215. if match == nil {
  216. return "", fmt.Errorf("未找到行号信息")
  217. }
  218. // 从匹配到的字符串中提取行号数字
  219. oldLineNumberStr := match[0]
  220. oldLineNumber, err := strconv.Atoi(oldLineNumberStr[len("line "):])
  221. if err != nil {
  222. return "", fmt.Errorf("解析行号失败: %v", err)
  223. }
  224. newLineNumber := oldLineNumber - frontNumber
  225. // 构建新的行号字符串
  226. newLineNumberStr := fmt.Sprintf("line %d", newLineNumber)
  227. // 替换原来的行号为新的行号
  228. newErrorText := re.ReplaceAllString(errorText, newLineNumberStr)
  229. return newErrorText, nil
  230. }