Commit a7cf4910 by hxw

update

parent d175d8db
...@@ -4,9 +4,13 @@ reload(sys); ...@@ -4,9 +4,13 @@ reload(sys);
from SQLHelper import * from SQLHelper import *
sys.setdefaultencoding('utf8'); sys.setdefaultencoding('utf8');
import pickle import pickle
import requests
class Action: class Action:
def __init__(self): def __init__(self):
self.botId = ""
self.userName = ""
self.botName = ""
self.waiting_str = "" self.waiting_str = ""
self.listening_str = "" self.listening_str = ""
self.http_str = "#actions\r\nname=pivot_httppost\r\naction=select\r\nstatus=waiting\r\n" self.http_str = "#actions\r\nname=pivot_httppost\r\naction=select\r\nstatus=waiting\r\n"
...@@ -17,6 +21,7 @@ class Action: ...@@ -17,6 +21,7 @@ class Action:
self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold","automatchurl" self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold","automatchurl"
,"serviceurl","pattern","conflict","importance","style"] ,"serviceurl","pattern","conflict","importance","style"]
self.load_global_config("global_config.txt") self.load_global_config("global_config.txt")
self.condition_name_list = []
self.sql_helper = SQLHelper() self.sql_helper = SQLHelper()
...@@ -29,54 +34,74 @@ class Action: ...@@ -29,54 +34,74 @@ class Action:
self.CONFIG_DIC[name] = value.strip() self.CONFIG_DIC[name] = value.strip()
def save_action(self,parameters): def generate_action(self,parameters):
flag = 1 flag = 1
try: try:
userName = parameters["userName"]#.encode("utf-8") userName = parameters["userName"]#.encode("utf-8")
self.userName = userName
conditionList = parameters["conditionList"] conditionList = parameters["conditionList"]
botName = parameters["botName"]
self.botName = botName
botId = parameters["botId"]
self.botId = botId
condition_name_list = ["process=nextStep="+condition["conditionName"]+"|"+condition["conditionName"]+"=active|"
for condition in conditionList]
print condition_name_list
self.all_nextStep = '\r\n'.join(condition_name_list)
for condition in conditionList: for condition in conditionList:
conditionName = condition["conditionName"]#.encode("utf-8") conditionName = condition["conditionName"]#.encode("utf-8")
relation = condition["relation"]#.encode("utf-8") relation = condition["relationHead"]+","+condition["relationName"]+","+condition["relationTail"]#.encode("utf-8")
question = condition["question"]#.encode("utf-8") question = condition["question"]#.encode("utf-8")
repeatList = condition["repeatList"] repeatList = condition["repeatList"]
active_flag = condition["active"] active_flag = condition["active"]
print conditionName
for i in range(3): for i in range(3):
self.insert_action_info(conditionName,active_flag,i) self.insert_action_info(conditionName,active_flag,i)
self.insert_condition(conditionName,relation,question,repeatList,i) self.insert_condition(conditionName,relation,question,repeatList,i)
self.insert_process(conditionName,repeatList,i) self.insert_process(conditionName,repeatList,i)
self.waiting_str += "process="+conditionName+"=+unknown|\r\n"+self.all_nextStep +"\n\r"
except KeyError: except KeyError:
return 2 return 2
userFile = open(userName+".txt",'w')
userData = open(userName+".data",'w') return flag
def save_action(self,parameters,auth):
userName = self.userName
botName = self.botName
botId = self.botId
userFile = open(userName+"-"+botName+"-action.txt",'w')
userData = open(userName+"-"+botName+"-action.data",'w')
pickle.dump(parameters,userData) pickle.dump(parameters,userData)
final_str = self.http_str + self.next_str+ self.waiting_str+self.listening_str+"\r\n\r\n\r\n" 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.write(final_str)
userFile.close() userFile.close()
userData.close() userData.close()
user_id = self.sql_helper.query_userid_by_username(userName) if botId == "" or botId == None or botId == "undefined":
print user_id flag = self.post_action(final_str,botName,parameters["cate"],parameters["cdt_name_ls"],auth)
if user_id != -1: print "flag:"+str(flag)
effect_row = self.sql_helper.update_action_text_by_userid(int(user_id),final_str)
if not effect_row:
flag = 3
else: else:
flag = 4 bot_id = self.sql_helper.query_userid_by_username(botName)
print bot_id
if bot_id != -1:
effect_row = self.sql_helper.update_action_text_by_userid(int(bot_id),final_str)
if not effect_row:
flag = 3
else:
flag = 4
return flag return flag
def reload_action(self,userName,botName):
def reload_action(self,userName): try:
userFile = open(userName+'.data','r') userFile = open(userName+"-"+botName+"-action.data",'r')
''' '''
actionList = [] actionList = []
action = {} action = {}
for line in userFile: for line in userFile:
name = line.strip().split("=")[0] name = line.strip().split("=")[0]
if name == "" : if name == "" :
if action != {}: if action != {}:
...@@ -84,9 +109,11 @@ class Action: ...@@ -84,9 +109,11 @@ class Action:
action = {} action = {}
else: else:
self.FUNC_MAP[name](line,action) self.FUNC_MAP[name](line,action)
''' '''
data = pickle.load(userFile) data = pickle.load(userFile)
userFile.close() userFile.close()
except IOError:
data = []
return {"actionList":data} return {"actionList":data}
...@@ -135,14 +162,14 @@ class Action: ...@@ -135,14 +162,14 @@ class Action:
def insert_action_info(self,conditionName,active_flag,flag): def insert_action_info(self,conditionName,active_flag,flag):
if not flag: if not flag:
status = "active" if active_flag==True else "waiting" status = "active" if active_flag==True else "waiting"
self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n" self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\nstyle=interrupt,httppost\r\n"
for key in self.ACTION_HEAD_INFO: for key in self.ACTION_HEAD_INFO:
if(self.CONFIG_DIC[key] != ""): if(self.CONFIG_DIC[key] != ""):
self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n'
self.waiting_str += "fellow=pivot_httppost\r\n" self.waiting_str += "fellow=pivot_httppost\r\n"
if flag == 1: if flag == 1:
status = "active" if active_flag==True else "listening" status = "listening"
self.listening_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n" self.listening_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\n"
for key in self.ACTION_HEAD_INFO: for key in self.ACTION_HEAD_INFO:
if(self.CONFIG_DIC[key] != ""): if(self.CONFIG_DIC[key] != ""):
...@@ -152,17 +179,17 @@ class Action: ...@@ -152,17 +179,17 @@ class Action:
def insert_condition(self,conditionName,relation,question,repeatList,flag): def insert_condition(self,conditionName,relation,question,repeatList,flag):
if not flag: if not flag:
self.waiting_str += "condition="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" self.waiting_str += "condition="+conditionName+"::1|"+relation+"|"+question+"|"
repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList]
reS = "~".join(repeat_str) reS = "~".join(repeat_str)
self.waiting_str += reS + "\r\n" self.waiting_str += reS + "\r\n"
if flag == 1: if flag == 1:
self.listening_str += "condition="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" self.listening_str += "condition="+conditionName+"|"+relation+"|"+question+"|"
repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList]
reS = "~".join(repeat_str) reS = "~".join(repeat_str)
self.listening_str += reS + "\r\n" self.listening_str += reS + "\r\n"
if flag == 2: if flag == 2:
self.http_str += "reference="+conditionName+"|#visitorname,"+relation+",?|"+question+"|" self.http_str += "reference="+conditionName+"|"+relation+"|"+question+"|"
repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList]
reS = "~".join(repeat_str) reS = "~".join(repeat_str)
self.http_str += reS + "\r\n" self.http_str += reS + "\r\n"
...@@ -178,6 +205,19 @@ class Action: ...@@ -178,6 +205,19 @@ class Action:
elif flag == 2: elif flag == 2:
self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n" self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n"
def post_action(self,action_str,botName,cate,cdt_name_ls,auth):
url= self.CONFIG_DIC["engine_url"]
payload= {'id':"",'botname':botName,'actions':action_str,'cate':cate,"cdt_name_ls":cdt_name_ls}
headers = {"Authorization":auth}
ret= requests.post(url,json=payload,headers=headers)
print "xx"
print ret.text
if(ret.status_code == 200):
return 1
elif(ret.status_code == 111):
return 2
else:
return 4
......
...@@ -25,11 +25,33 @@ class BackgroundConfig(): ...@@ -25,11 +25,33 @@ class BackgroundConfig():
name,value = line.split("=") name,value = line.split("=")
self.CONFIG_DIC[name] = value.strip() self.CONFIG_DIC[name] = value.strip()
def reload_background_config(self,userName,botName):
try:
userFile = open(userName+"-"+botName+'-config.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()
except IOError:
data = []
return {"configList":data}
def save_background_config(self,parameters): def save_background_config(self,parameters):
flag = 1 flag = 1
try: try:
userName = parameters["userName"].strip() userName = parameters["userName"].strip()
configList = parameters["configList"] configList = parameters["configList"]
botName = parameters["botName"].strip()
for config in configList: for config in configList:
currentPremiseList = config["currentPremiseList"] currentPremiseList = config["currentPremiseList"]
reply = config["reply"].strip() if config["reply"] != "" else " " reply = config["reply"].strip() if config["reply"] != "" else " "
...@@ -53,6 +75,10 @@ class BackgroundConfig(): ...@@ -53,6 +75,10 @@ class BackgroundConfig():
config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n' config_line = curPreStr + "|"+hisPreStr+"|match|=>|"+reply+"|nextStep="+nextStep+'\n'
self.config_string += config_line self.config_string += config_line
print self.config_string print self.config_string
if flag == 1:
userData = open(userName+"-"+botName+'-config.data','w')
pickle.dump(parameters,userData)
userData.close()
except KeyError: except KeyError:
flag = 2 flag = 2
......
...@@ -38,4 +38,35 @@ class SQLHelper: ...@@ -38,4 +38,35 @@ class SQLHelper:
cur.close() cur.close()
conn.close() conn.close()
'''
def create_new_bot(self,userName,botName)
try:
conn = pymysql.connect(**self.conn_dict)
sql = "INSERT INTO `users` (`id`, `username`, `nickname`, `password`, `firstname`, `lastname`, `status`, `action`, `timestamp`, `email`, `session_key`, `title`, `description`, `category`, `subcategory`, `welcome`, `terminal`, `url`, `website`, `icon`, `volume`, `user_interactions`, `user_chats`, `active_link`) VALUES (NULL, %s, 'cc', 'abc123', ' ', ' ', 'active', '', CURRENT_TIMESTAMP, ' abc@qiwu.ai', ' ', ' ', '', ' ', ' ', ' ', ' ', '', ' ', ' ', '0', '0', '0', '')"%(userName+"asdfghg"+"botName")
cur = conn.cursor()
sta = cur.execute(sql)
conn.commit()
if sta == 1:
return 1
else:
return 0
except Exception as e:
raise e
finally:
conn.close()
cur.close()
def insert_action_text_by_userid(self,userid,action_str):
try:
conn = pymusql.connect(**self.conn_dict)
sql = "INSERT INTO `units` (`id`, `user_id`, `name`, `description`, `status`, `timestamp`, `text`, `xml`) VALUES (NULL, %d, 'actions\r\n', '', 'ready', CURRENT_TIMESTAMP, 'xxx', '')"
'''
...@@ -24,7 +24,11 @@ def save_action(): ...@@ -24,7 +24,11 @@ def save_action():
if request.method == 'POST': if request.method == 'POST':
action = Action() action = Action()
dc = json.loads(request.get_data().decode("utf8")) dc = json.loads(request.get_data().decode("utf8"))
flag = action.save_action(dc) flag = action.generate_action(dc)
if flag == 1:
auth = request.headers['Authorization']
action.save_action(dc,auth)
print flag print flag
if flag == 1: if flag == 1:
return "success" return "success"
...@@ -43,11 +47,13 @@ def reload_action(): ...@@ -43,11 +47,13 @@ def reload_action():
action = Action() action = Action()
dc = json.loads(request.get_data().decode("utf8")) dc = json.loads(request.get_data().decode("utf8"))
userName = dc["userName"] userName = dc["userName"]
botName = dc["botName"]
return jsonify(action.reload_action(userName)) return jsonify(action.reload_action(userName))
if request.method == "GET": if request.method == "GET":
action = Action() action = Action()
userName = request.values.get("userName") userName = request.values.get("userName")
return jsonify(action.reload_action(userName)) botName = request.values.get("botName")
return jsonify(action.reload_action(userName,botName))
@app.route("/saveBackgroundConfig", methods=["POST","OPTIONS"]) @app.route("/saveBackgroundConfig", methods=["POST","OPTIONS"])
def save_background_config(): def save_background_config():
...@@ -76,8 +82,10 @@ def save_background_config(): ...@@ -76,8 +82,10 @@ def save_background_config():
@app.route("/reloadBackgroundConfig",methods=["GET"]) @app.route("/reloadBackgroundConfig",methods=["GET"])
def reload_action_config(): def reload_action_config():
if request.method == "GET": if request.method == "GET":
action = Action() userName = request.values.get("userName")
return jsonify(action.reload_action_config()) botName = request.values.get("botName")
bg_config = BackgroundConfig()
return jsonify(bg_config.reload_background_config(userName,botName))
......
...@@ -11,14 +11,15 @@ import json ...@@ -11,14 +11,15 @@ import json
class UserBehavior(TaskSet): class UserBehavior(TaskSet):
def on_start(self): def on_start(self):
pass pass
'''
@task(1) @task(1)
def index2(self): def index2(self):
data = {"userName":"hxw2303632" data = {"userName":"ccc","botName":"hxw2303632","botId":"undefined"
,"conditionList":[ {"conditionName":u"xihuan","relation":u"relation-find-xihuan","question":u"你玩多久了?", ,"conditionList":[ {"active":True,"conditionName":u"xihuan","relationHead":"#visitorname","relationTail":"?","relationName":u"relation-find-xihuan","question":u"你玩多久了?",
"repeatList":[{"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":u"+dota+王者荣耀"}, {"repeatString":u"#visitorname喜欢玩[]",u"repeatKeywords":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"你管我玩多久了?", {"active":False
,"conditionName":u"buxihuan","relationHead":"#visitorname","relationTail":"?","relationName":u"relation-find-xihuan","question":u"你管我玩多久了?",
"repeatList":[{"repeatString":u"#visitorname不喜欢玩[]",u"repeatKeywords":str(time.time())}] "repeatList":[{"repeatString":u"#visitorname不喜欢玩[]",u"repeatKeywords":str(time.time())}]
} }
]} ]}
...@@ -26,7 +27,7 @@ class UserBehavior(TaskSet): ...@@ -26,7 +27,7 @@ class UserBehavior(TaskSet):
''' '''
@task(1) @task(1)
def index(self): def index(self):
data = {"userName":"hxw","configList":[ data = {"botName":"hxw2303632""userName":"hxw","configList":[
{"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}], {"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}],
"historyPremiseList":[{"actionName":"","keywords":""}] }, "historyPremiseList":[{"actionName":"","keywords":""}] },
{"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}], {"nextStep":"there","reply":"say some thing","currentPremiseList":[{"actionName":"ask","keywords":"+xihuan+dota"}],
...@@ -34,7 +35,7 @@ class UserBehavior(TaskSet): ...@@ -34,7 +35,7 @@ class UserBehavior(TaskSet):
} }
]} ]}
self.client.post('/saveBackgroundConfig',data=None,json=data) self.client.post('/saveBackgroundConfig',data=None,json=data)
'''
class WebsiteUser(HttpLocust): class WebsiteUser(HttpLocust):
......
import requests
def sign_in(userName,botName):
url = "http://192.168.1.81:8080/km/register_ch.php"
payload= {'name':userName+"123456"+botName,'password':"123456789asdfgh","email":"123456@qq.com","cpassword":"123456asdfgh"}
ret= requests.post(url,data=payload)
print ret.text
if(ret.status_code == 200):
return 1
elif(ret.status_code == 111):
return 2
else:
return 4
sign_in("hxw2303632","xxxf")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment