From d175d8dbd299e334e6f701d4f51d8bd035b6d22d Mon Sep 17 00:00:00 2001 From: hxw Date: Thu, 21 Jun 2018 16:24:10 +0800 Subject: [PATCH] update code of generate action --- GenerateAction/Action.py | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GenerateAction/BackgroundConfig.py | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GenerateAction/SQLHelper.py | 41 +++++++++++++++++++++++++++++++++++++++++ GenerateAction/action_service.py | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ GenerateAction/locustfile.py | 44 ++++++++++++++++++++++++++++++++++++++++++++ GenerateAction/post_test.py | 29 +++++++++++++++++++++++++++++ 6 files changed, 462 insertions(+) create mode 100644 GenerateAction/Action.py create mode 100644 GenerateAction/BackgroundConfig.py create mode 100644 GenerateAction/SQLHelper.py create mode 100644 GenerateAction/action_service.py create mode 100644 GenerateAction/locustfile.py create mode 100644 GenerateAction/post_test.py diff --git a/GenerateAction/Action.py b/GenerateAction/Action.py new file mode 100644 index 0000000..1541e61 --- /dev/null +++ b/GenerateAction/Action.py @@ -0,0 +1,185 @@ +#coding:utf8 +import sys; +reload(sys); +from SQLHelper import * +sys.setdefaultencoding('utf8'); +import pickle + +class Action: + def __init__(self): + self.waiting_str = "" + self.listening_str = "" + self.http_str = "#actions\r\nname=pivot_httppost\r\naction=select\r\nstatus=waiting\r\n" + self.next_str = "" + self.FUNC_MAP = {"action":self.parse_name,"status":self.parse_status,"condition":self.parse_condition + ,"conflict":self.parse_conflict,"process":self.parse_process} + self.CONFIG_DIC = {} #存储全局配置文件的信息 + self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold","automatchurl" + ,"serviceurl","pattern","conflict","importance","style"] + self.load_global_config("global_config.txt") + self.sql_helper = SQLHelper() + + + def load_global_config(self,engine_config_file): + config = open(engine_config_file,'r') + for line in config: + if line.strip() == "": + continue + name,value = line.split("=") + self.CONFIG_DIC[name] = value.strip() + + + def save_action(self,parameters): + flag = 1 + try: + userName = parameters["userName"]#.encode("utf-8") + conditionList = parameters["conditionList"] + + + for condition in conditionList: + conditionName = condition["conditionName"]#.encode("utf-8") + relation = condition["relation"]#.encode("utf-8") + question = condition["question"]#.encode("utf-8") + repeatList = condition["repeatList"] + active_flag = condition["active"] + + for i in range(3): + self.insert_action_info(conditionName,active_flag,i) + self.insert_condition(conditionName,relation,question,repeatList,i) + self.insert_process(conditionName,repeatList,i) + except KeyError: + return 2 + userFile = open(userName+".txt",'w') + userData = open(userName+".data",'w') + pickle.dump(parameters,userData) + final_str = self.http_str + self.next_str+ self.waiting_str+self.listening_str+"\r\n\r\n\r\n" + userFile.write(final_str) + userFile.close() + userData.close() + user_id = self.sql_helper.query_userid_by_username(userName) + print user_id + if user_id != -1: + effect_row = self.sql_helper.update_action_text_by_userid(int(user_id),final_str) + if not effect_row: + flag = 3 + else: + flag = 4 + + + return flag + + + + + def reload_action(self,userName): + userFile = open(userName+'.data','r') + ''' + actionList = [] + action = {} + for line in userFile: + name = line.strip().split("=")[0] + if name == "" : + if action != {}: + actionList.append(action) + action = {} + else: + self.FUNC_MAP[name](line,action) + ''' + data = pickle.load(userFile) + userFile.close() + return {"actionList":data} + + + def parse_name(self,text,action): + _,name = text.split("=") + + action["actionName"] = name + def parse_status(self,text,action): + _,status = text.split("=") + action["status"] = status + + def parse_conflict(self,text,action): + _,conflictStr = text.split("=") + conflictList = conflictStr.split(",") + action["conflictList"] = [] + for conflict in conflictList: + action["conflictList"].append(conflict) + + def parse_condition(self,text,action): + condition,relation,question,repeatStr = text.split("|") + _,conditionName = condition.split("=") + action["conditionName"] = conditionName + action["relation"] = relation + action["question"] = question + repeatList = repeatStr.split(",") + action["repeatList"] = [] + for repeat in repeatList: + repeatDic = {} + re,keywords = repeat.split("=") + repeatDic["repeatString"] = re + repeatDic["repeatKeywords"] = keywords + action["repeatList"].append(repeatDic) + + def parse_process(self,text,action): + processStr,nextAction,reply = text.split("|") + _,proName,keywords = processStr.split("=") + process = {} + if action["processList"] == None: + action["processList"] = [] + process["processName"] = proName + process["processKeyWords"] = keywords + process["nextAction"] = nextAction + process["reply"] = reply + action["processList"].append(process) + + def insert_action_info(self,conditionName,active_flag,flag): + if not flag: + status = "active" if active_flag==True else "waiting" + self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n" + for key in self.ACTION_HEAD_INFO: + if(self.CONFIG_DIC[key] != ""): + self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' + self.waiting_str += "fellow=pivot_httppost\r\n" + + if flag == 1: + status = "active" if active_flag==True else "listening" + self.listening_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n" + for key in self.ACTION_HEAD_INFO: + if(self.CONFIG_DIC[key] != ""): + self.listening_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' + self.listening_str += "fellow=pivot_httppost\r\n" + + + def insert_condition(self,conditionName,relation,question,repeatList,flag): + if not flag: + self.waiting_str += "condition="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" + repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] + reS = "~".join(repeat_str) + self.waiting_str += reS + "\r\n" + if flag == 1: + self.listening_str += "condition="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" + repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] + reS = "~".join(repeat_str) + self.listening_str += reS + "\r\n" + if flag == 2: + self.http_str += "reference="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" + repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] + reS = "~".join(repeat_str) + self.http_str += reS + "\r\n" + + + def insert_process(self,conditionName,repeatList,flag): + if not flag: + for repeat in repeatList: + self.waiting_str += "process="+conditionName+"=+"+repeat["repeatKeywords"]+"|pivot_httppost=active|\r\n" + elif flag == 1: + for repeat in repeatList: + self.listening_str += "process="+conditionName+"=+"+repeat["repeatKeywords"]+"|pivot_httppost=active|\r\n" + elif flag == 2: + self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n" + + + + + + diff --git a/GenerateAction/BackgroundConfig.py b/GenerateAction/BackgroundConfig.py new file mode 100644 index 0000000..a09c537 --- /dev/null +++ b/GenerateAction/BackgroundConfig.py @@ -0,0 +1,75 @@ +#coding:utf8 +import requests +import json +from Action import * +import sys; +reload(sys); +sys.setdefaultencoding('utf8'); + +class BackgroundConfig(): + ''' + 根据post的参数保存成配置文件的形式 + ''' + + def __init__(self): + self.config_string = "" + self.CONFIG_DIC = {} #存储全局配置文件的信息 + self.load_global_config("global_config.txt") + + + def load_global_config(self,engine_config_file): + config = open(engine_config_file,'r') + for line in config: + if line.strip() == "": + continue + name,value = line.split("=") + self.CONFIG_DIC[name] = value.strip() + + def save_background_config(self,parameters): + flag = 1 + try: + userName = parameters["userName"].strip() + configList = parameters["configList"] + for config in configList: + currentPremiseList = config["currentPremiseList"] + reply = config["reply"].strip() if config["reply"] != "" else " " + nextStep = config["nextStep"].strip() + historyPremiseList = config["historyPremiseList"] + if nextStep == "" : + flag = 2 + break + + if len(currentPremiseList) == 1 and currentPremiseList[0]["keywords"] == "": + flag = 3 + break + curPreStr = ','.join([currentPremise["actionName"]+"="+currentPremise["keywords"] for currentPremise in currentPremiseList]) + if historyPremiseList != [] and historyPremiseList[0]["keywords"] != "": + hisPreStr = ','.join([historyPremise["actionName"]+"="+historyPremise["keywords"] for historyPremise in historyPremiseList]) + else: + hisPreStr = "" + if hisPreStr == "": + config_line = curPreStr + "| |"+"match|=>|"+reply+"|nextStep="+nextStep+'\n' + else: + config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n' + self.config_string += config_line + print self.config_string + + except KeyError: + flag = 2 + + + return flag + + def post_bg_config(self,userName): + url= self.CONFIG_DIC["config_post_url"] + payload= {'userName':userName,'config_string':self.config_string} + + ret= requests.post(url,data=payload) + if(ret.status_code == 200): + return 1 + elif(ret.status_code == 111): + return 2 + else: + return 4 + + diff --git a/GenerateAction/SQLHelper.py b/GenerateAction/SQLHelper.py new file mode 100644 index 0000000..79947ec --- /dev/null +++ b/GenerateAction/SQLHelper.py @@ -0,0 +1,41 @@ +import pymysql + +class SQLHelper: + def __init__(self): + self.conn_dict = dict(host="192.168.1.81",port=3306,user="root",passwd="admin",db="chatCN",charset="utf8") + def query_userid_by_username(self,username): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "select id from users where username='%s'"%username + parameters = (username) + cur = conn.cursor() + cur.execute(sql) +#cur.execute(sql,username) + results = cur.fetchall() + conn.commit() + if len(results): + return results[0][0] + else : + return -1 + except Exception as e: + raise e + finally: + cur.close() + conn.close() + + + def update_action_text_by_userid(self,userid,action_str): + try: + conn = pymysql.connect(**self.conn_dict) + sql = "update units set text = '%s' where name='actions' and user_id=%d"%(action_str,userid) + cur = conn.cursor(cursor=pymysql.cursors.DictCursor) + effect_row = cur.execute(sql) + conn.commit() + return effect_row + except Exception as e: + raise e + finally: + cur.close() + conn.close() + + diff --git a/GenerateAction/action_service.py b/GenerateAction/action_service.py new file mode 100644 index 0000000..0cdcdd8 --- /dev/null +++ b/GenerateAction/action_service.py @@ -0,0 +1,88 @@ +#coding:utf8 +from flask import Flask +from flask import request +from flask import jsonify +from flask import make_response +from flask_cors import * +import json +from functools import wraps +from Action import * +from BackgroundConfig import * +import sys; +reload(sys); +sys.setdefaultencoding('utf8'); + + + +app = Flask(__name__) +CORS(app, supports_credentials=True) + + + +@app.route('/saveAction', methods=[ 'POST',"OPTIONS"]) +def save_action(): + if request.method == 'POST': + action = Action() + dc = json.loads(request.get_data().decode("utf8")) + flag = action.save_action(dc) + print flag + if flag == 1: + return "success" + elif flag == 2: + return "lack parameter" + elif flag == 3: + return "sql error" + elif flag == 4: + return "no such user" + elif request.method == "OPTIONS": + return "do it" + +@app.route("/reloadAction", methods=["GET","POST"]) +def reload_action(): + if request.method == "POST": + action = Action() + dc = json.loads(request.get_data().decode("utf8")) + userName = dc["userName"] + return jsonify(action.reload_action(userName)) + if request.method == "GET": + action = Action() + userName = request.values.get("userName") + return jsonify(action.reload_action(userName)) + +@app.route("/saveBackgroundConfig", methods=["POST","OPTIONS"]) +def save_background_config(): + if request.method == 'POST': + bg_config = BackgroundConfig() + parameters = json.loads(request.get_data().decode("utf8")) + flag = bg_config.save_background_config(parameters) + + if flag == 1: + flag = bg_config.post_bg_config(parameters["userName"]) + + print flag + if flag == 1: + return "success" + elif flag == 2: + return "lack parameter" + elif flag == 3: + return "current information is empty" + elif flag == 4: + return "post fail" + + elif request.method == "OPTIONS": + return "do it" + + +@app.route("/reloadBackgroundConfig",methods=["GET"]) +def reload_action_config(): + if request.method == "GET": + action = Action() + return jsonify(action.reload_action_config()) + + + +if __name__ == '__main__': + app.run(threaded=True,host="0.0.0.0", + port=1111,) + + diff --git a/GenerateAction/locustfile.py b/GenerateAction/locustfile.py new file mode 100644 index 0000000..175ea3b --- /dev/null +++ b/GenerateAction/locustfile.py @@ -0,0 +1,44 @@ +# coding:utf-8 +import sys +reload(sys) +sys.setdefaultencoding('utf8') +import time +from locust import HttpLocust,TaskSet,task +import json + + + +class UserBehavior(TaskSet): + def on_start(self): + pass + ''' + @task(1) + def index2(self): + data = {"userName":"hxw2303632" + ,"conditionList":[ {"conditionName":u"xihuan","relation":u"relation-find-xihuan","question":u"你玩多久了?", + "repeatList":[{"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":u"+dota+王者荣耀"}, {"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":u"+手游+休闲游戏+你管我"}] + }, + {"conditionName":u"buxihuan","relation":u"relation-find-buxihuan","question":u"你管我玩多久了?", + "repeatList":[{"repeatString":u"#visitorname不喜欢玩[]",u"repeatKeywords":str(time.time())}] + } + ]} + self.client.post('/saveAction',data=None,json=data) + ''' + @task(1) + def index(self): + data = {"userName":"hxw","configList":[ + {"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}], + "historyPremiseList":[{"actionName":"","keywords":""}] }, + {"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}], + "historyPremiseList":[{"actionName":"","keywords":""}] + } + ]} + self.client.post('/saveBackgroundConfig',data=None,json=data) + + + +class WebsiteUser(HttpLocust): + task_set = UserBehavior + host = "http://192.168.1.178:1111" + min_wait = 1000 + max_wait = 1000 diff --git a/GenerateAction/post_test.py b/GenerateAction/post_test.py new file mode 100644 index 0000000..15aaa75 --- /dev/null +++ b/GenerateAction/post_test.py @@ -0,0 +1,29 @@ +#coding:utf-8 +from flask import Flask +from flask import request +from flask import jsonify +import json + + + +app = Flask(__name__) + + + + +@app.route('/test', methods=['GET', 'POST']) +def login(): + if request.method == 'POST': + dc = json.loads(request.get_data().decode("utf8")) + if(dc.has_key("curInfoPoint")): + return jsonify({"parameter":"捷豹"}) + else: + return jsonify(dc) + else: + return "incorrect method,use POST instead!" + +if __name__ == '__main__': + app.run(host="0.0.0.0", + port=8888,) + + -- libgit2 0.27.1