base_from_python.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. "strings"
  13. )
  14. func Test() (err error) {
  15. defer func() {
  16. if err != nil {
  17. fmt.Println("err:", err)
  18. }
  19. }()
  20. ///usr/local/bin/python3.9
  21. //exec.Command("bin/bash", "-c")
  22. //cmd := exec.Command("/usr/local/bin/python3.9", "-c", "/Users/roc/go/src/eta/eta_index_lib/test2.py")
  23. //cmd := exec.Command("python3", "-c", "./test2.py")
  24. cmd := exec.Command("python3", "/Users/roc/go/src/eta/eta_index_lib/test2.py")
  25. outputByte, err := cmd.Output()
  26. //fmt.Println(err)
  27. fmt.Println("start")
  28. if err != nil {
  29. return
  30. }
  31. fmt.Println(string(outputByte))
  32. arr := strings.Split(string(outputByte), "result=")
  33. arrLen := len(arr)
  34. //fmt.Println(arr)
  35. if arrLen <= 1 {
  36. err = fmt.Errorf("python运算结果异常")
  37. return
  38. }
  39. resultStr := arr[arrLen-1]
  40. fmt.Println(resultStr)
  41. var dataMap map[string]float64
  42. json.Unmarshal([]byte(resultStr), &dataMap)
  43. fmt.Println(dataMap)
  44. //i, err := python3.Py_Main(os.Args)
  45. //if err != nil {
  46. // fmt.Printf("error launching the python interpreter: %s\n", err)
  47. // os.Exit(1)
  48. //}
  49. ////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"
  50. ////i := python3.PyRun_SimpleString(commStr)
  51. //fmt.Println(i)
  52. return
  53. }
  54. // EdbDataStrFromPython 通过python代码获取到的指标数据(interface数据)
  55. type EdbDataStrFromPython struct {
  56. Date map[int]string `json:"date"`
  57. Value map[int]interface{} `json:"value"`
  58. }
  59. // ExecPythonCode 执行Python代码
  60. func ExecPythonCode(edbCode, reqCode string) (dataMap models.EdbDataFromPython, err error, errMsg string) {
  61. defer func() {
  62. if err != nil {
  63. fmt.Println("err:", err)
  64. }
  65. }()
  66. codeStr := strings.ToLower(reqCode)
  67. // 限制python代码的执行,如果包含特殊的关键词,则报错
  68. if strings.Contains(codeStr, "drop table") || strings.Contains(codeStr, "delete") || strings.Contains(codeStr, "update") || strings.Contains(codeStr, "alter") || strings.Contains(codeStr, "truncate") {
  69. err = fmt.Errorf("不支持该命令")
  70. return
  71. }
  72. //获取python文件的绝对地址
  73. pythonFile, err := getPythonFileAbsolutePath(edbCode)
  74. if err != nil {
  75. return
  76. }
  77. pythonCodeStr := getPythonFrontStr() + reqCode + getPythonLaterStr()
  78. fileHandle, err := os.OpenFile(pythonFile, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0766)
  79. if err != nil {
  80. return
  81. }
  82. defer func() {
  83. //os.Remove(pythonFile)
  84. }()
  85. _, err = fileHandle.Write([]byte(pythonCodeStr))
  86. if err != nil {
  87. return
  88. }
  89. fileHandle.Close()
  90. cmd := exec.Command(utils.PYTHON_PATH, pythonFile)
  91. var out, errMsgOut bytes.Buffer
  92. cmd.Stdout = &out
  93. cmd.Stderr = &errMsgOut
  94. err = cmd.Run()
  95. if err != nil {
  96. errMsg = errMsgOut.String()
  97. return
  98. }
  99. outputByte := out.String()
  100. if err != nil {
  101. return
  102. }
  103. //fmt.Println(string(outputByte))
  104. arr := strings.Split(string(outputByte), "result=")
  105. arrLen := len(arr)
  106. //fmt.Println(arr)
  107. if arrLen <= 1 {
  108. err = fmt.Errorf("python运算结果异常")
  109. return
  110. }
  111. resultStr := arr[arrLen-1]
  112. //fmt.Println(resultStr)
  113. var dataMapStr EdbDataStrFromPython
  114. //先将value转为interface
  115. err = json.Unmarshal([]byte(resultStr), &dataMapStr)
  116. if err != nil {
  117. return
  118. }
  119. dataMap.Date = make(map[int]string)
  120. dataMap.Value = make(map[int]float64)
  121. //将value为nil的给过滤掉
  122. i := 0
  123. lenData := len(dataMapStr.Date)
  124. for k := 0; k < lenData; k++ {
  125. date := dataMapStr.Date[k]
  126. tmpValue := dataMapStr.Value[k]
  127. if reflect.TypeOf(tmpValue) != nil {
  128. if reflect.TypeOf(tmpValue).Kind() == reflect.Float64 {
  129. dataMap.Date[i] = date
  130. dataMap.Value[i], _ = decimal.NewFromFloat(reflect.ValueOf(tmpValue).Float()).Truncate(4).Float64() //保留4位小数
  131. i++
  132. }
  133. }
  134. }
  135. //err = json.Unmarshal([]byte(resultStr), &dataMap)
  136. //fmt.Println(dataMap)
  137. return
  138. }
  139. // getPythonFileAbsolutePath 获取python文件的绝对地址
  140. func getPythonFileAbsolutePath(edbCode string) (pythonFile string, err error) {
  141. uploadDir := utils.STATIC_DIR + "python/"
  142. err = os.MkdirAll(uploadDir, 0766)
  143. if err != nil {
  144. return
  145. }
  146. pythonFile = uploadDir + fmt.Sprint(edbCode, "_", utils.GetRandDigit(16), ".py")
  147. if utils.RunMode != "release" {
  148. dir, tmpErr := os.Getwd()
  149. if tmpErr != nil {
  150. err = tmpErr
  151. return
  152. }
  153. pythonFile = dir + "/" + pythonFile
  154. }
  155. return
  156. }
  157. // getPythonFrontStr 获取python前面的代码
  158. func getPythonFrontStr() string {
  159. //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"
  160. //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)
  161. str := fmt.Sprintf("#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport json\n\nimport pandas as pd\nfrom sqlalchemy import create_engine\nfrom urllib.parse import quote_plus\nimport pytz\n\nencoded_host = quote_plus(\"%s\")\nencoded_user = quote_plus(\"%s\")\nencoded_password = quote_plus(\"%s\")\nencoded_database = quote_plus(\"%s\")\n\ndb = create_engine(f'mysql+mysqlconnector://{encoded_user}:{encoded_password}@{encoded_host}:3306/{encoded_database}')\npandas_fetch_all = pd.read_sql_query\n\n", utils.PYTHON_MYSQL_HOST, utils.PYTHON_MYSQL_USER, utils.PYTHON_MYSQL_PASSWD, utils.PYTHON_MYSQL_DB)
  162. // mongo部分
  163. if utils.PYTHON_MONGO_HOST != `` {
  164. str += getPythonFront2Str()
  165. }
  166. // 格式化数据部分
  167. str += getPythonFront3Str()
  168. return str
  169. }
  170. // getPythonFront2Str
  171. // @Description: mongo部分
  172. // @author: Roc
  173. // @datetime 2024-05-07 18:38:03
  174. // @return string
  175. func getPythonFront2Str() string {
  176. str := fmt.Sprintf("\nfrom pymongo import MongoClient\nimport pytz\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)
  177. return str
  178. }
  179. // getPythonFront3Str
  180. // @Description: 第三部分
  181. // @author: Roc
  182. // @datetime 2024-05-07 18:37:56
  183. // @return string
  184. func getPythonFront3Str() string {
  185. 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")
  186. return str
  187. }
  188. // getPythonLaterStr 获取python结尾的代码
  189. func getPythonLaterStr() string {
  190. return "\n\nprint(\"result=\", result.to_json())\n"
  191. }