# coding:utf8 from flask import Flask from flask import request, send_from_directory from flask import jsonify, make_response from flask_cors import CORS import json from Action import Action from BackgroundConfig import BackgroundConfig import sys reload(sys) sys.setdefaultencoding('utf8') import time app = Flask(__name__) CORS(app, supports_credentials=True) @app.route('/saveAction', methods=['POST', "OPTIONS"]) def save_action(): if request.method == 'POST': action = Action() bg_config = BackgroundConfig() dc = json.loads(request.get_data().decode("utf8")) flag = action.generate_action(dc) if flag == 1: auth = request.headers['Authorization'] action.save_action(dc, auth) bg_config.post_single_config_to_backend({"type": "extra_info", "configId": "", "userName": dc["botName"], "configData": "-extraInfo-|activeAction|" + action.active}) if(dc["botId"] != "undefined"): bg_config.change_bg_config(dc["botId"], dc["userName"], dc["botName"], dc["conditionList"]) 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")) botId = dc["botId"] return jsonify(action.reload_action(botId)) if request.method == "GET": action = Action() userName = request.values.get("userName") botName = request.values.get("botName") botId = request.values.get("botId") return jsonify(action.reload_action(userName, botName, botId)) @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.generate_background_config(parameters) if flag == 1: flag = bg_config.save_bg_config(parameters) if flag == 1: flag = bg_config.post_bg_config(parameters["botName"]) if flag == 1 and parameters["sayGoodBye"] != "": action = Action() flag = action.update_goodbye(parameters["sayGoodBye"], parameters["botId"]) # 根据flag返回结果 if flag == 1: return "success" elif flag == 2: return "lack parameter" elif flag == 3: return "sql error" 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": userName = request.values.get("userName") botName = request.values.get("botName") botId = request.values.get("botId") bg_config = BackgroundConfig() return jsonify(bg_config.reload_background_config(userName, botName, botId)) @app.route("/save2file", methods=["POST", "OPTIONS"]) def save_config_file(): ''' 保存备份文件 ''' if request.method == "POST": action = Action() bg = BackgroundConfig() dc = json.loads(request.get_data().decode("utf8")) botId = dc["botId"] userName = dc["botName"] botName_yhm =dc["botName_yhm"] auth = request.headers['Authorization'] cate, cdt_name_ls = action.get_cdt_ls(botId, auth) categoryDataset = action.data_helper.query_category_all_by_botId(botId) conditionDataset = action.data_helper.query_condition_all_by_botId(botId) configDataset = action.data_helper.query_config_all_by_botId(botId) configText = bg.get_config_text(dc) data = {"botId": botId, "categoryDataset": categoryDataset, "conditionDataset": conditionDataset, "configDataset": configDataset, "cate": cate, "cdt_name_ls": cdt_name_ls, "botName_yhm": botName_yhm, "configText": configText, "userName": userName} # if "absPath" in dc: # abs_path = dc["absPath"] # data_path = abs_path + "/"+ userName + "-" + botName + "-" + data_type + ".json" # else: # data_path = os.path.abspath('.')+ "/tmp/"+ userName + "-" + botName + "-" + data_type + ".json" data_path = './tmp' file_name = botId + "-" + ".backup" with open(data_path + "/" + file_name, 'w') as f: f.write(json.dumps(data, ensure_ascii=False)) # return send_from_directory(data_path, file_name, as_attachment=True) return "download/"+ file_name elif request.method == "OPTIONS": return "do it" @app.route("/download/", methods=["GET"]) def download_file(filename): ''' 返回备份 ''' directory = './tmp' response = make_response(send_from_directory(directory, filename, as_attachment=True)) response.headers["Content-Disposition"] = "attachment; filename={}".format(filename.encode().decode('latin-1')) return response @app.route("/dataRecovery", methods=["POST", "OPTIONS"]) def data_recovery(): if request.method == "POST": bg = BackgroundConfig() action = Action() dc = json.loads(request.get_data().decode("utf8")) botId = dc["botId"] dc["data"]["botId"] = botId dc = dc["data"] dc["auth"] = request.headers['Authorization'] categoryDataset = dc["categoryDataset"] configDataset = dc["configDataset"] conditionDataset = dc["conditionDataset"] configText = dc["configText"] if dc["configText"] != "查无此bot" else "" categoryDataset = tuple([tuple([str(a) for a in d]) for d in categoryDataset]) conditionDataset = tuple([tuple([str(a) for a in d]) for d in conditionDataset]) configDataset = tuple([tuple([str(a) for a in d]) for d in configDataset]) ''' bg.data_helper.clear_user_data(botId) print "insert category" bg.data_helper.batch_insert_category(botId, categoryDataset) print "insert config" bg.data_helper.batch_insert_config(botId, configDataset) print "insert condition" bg.data_helper.batch_insert_condition(botId, conditionDataset) bg.post_single_config_to_backend({"userName": dc["userName"], "type": "batch_update", "configId": -1, "configData": configText}) action.query_post_action(dc) ''' else: return "do it" return "1" @app.route("/configProcess", methods=["POST", "OPTIONS"]) def config_processing(): if request.method == "POST": dc = json.loads(request.get_data().decode("utf8")) process_type = dc["type"] bg = BackgroundConfig() dc["back"] = bg FUNC_MAP = {"delete_config": bg.delete_config, "insert_config": bg.insert_config, "update_config": bg.update_config, "query_config": bg.query_config, # "query_config": bg.query_sleeping_config, "insert_category": bg.insert_category, "update_category": bg.update_category, "query_category": bg.query_category, "query_sleeping_config": bg.query_sleeping_config, "delete_category": bg.delete_category} flag, data = FUNC_MAP[process_type](dc) # print "flag", flag, "data", data if flag == 1 and process_type in ["delete_config", "update_config"]: # print "post data:", data flag = bg.post_single_config_to_backend({"type": process_type, "configId": dc["configId"], "userName": elif process_type == "insert_config" and flag != 0: flag = bg.post_single_config_to_backend({"type": process_type, "configId": flag, "userName": dc["botNam elif process_type in["query_config", "query_sleeping_config"] and flag == 1: return jsonify({"configList": data}) # return json.dumps(data, ensure_ascii=False) if process_type == "insert_config": return str(flag) else: return json.dumps(data, ensure_ascii=False) elif request.method == "OPTIONS": return "do it" @app.route("/getNextStepException", methods=["GET", "OPTIONS"]) def get_next_step_exception(): if request.method == "GET": return "active known" elif request.method == "OPTIONS": return "do it" @app.route("/conditionProcess", methods=["POST", "OPTIONS"]) def condition_processing(): ''' condition的处理接口 ''' if request.method == "POST": dc = json.loads(request.get_data().decode("utf8")) dc["auth"] = request.headers['Authorization'] # 获得engine提交权限 process_type = dc["type"] action = Action() bg_config = BackgroundConfig() if dc["botId"] == "undefined": # botId不存在就新建bot flag, botId = action.bot_initialization(dc) dc["botId"] = botId elif process_type not in ["update_goodbye", "query_condition", "query_category"]: # 将请求参数中的cdt_name_ls和引擎中的cdt_name_ls合并 action.merge_cdt_name_ls_from_engine(dc) flag = action.bot_initialization(dc) FUNC_MAP = {"delete_condition": action.delete_condition, # 返回0或1 "insert_condition": action.insert_condition, # 返回conditionId "update_condition": action.update_condition, # 返回0或1 "query_condition": action.query_condition, # 返回condition列表 "query_category": action.query_category, "change_active": action.change_active, "update_goodbye": action.update_goodbye} # 返回类别栏 flag, message = FUNC_MAP[process_type](dc) print process_type # print "flag", flag, "message", message if flag == 1: # 操作执行成功 if process_type == "query_category": return jsonify({"category": message}) elif process_type == "query_condition": return jsonify(message) if process_type == "update_condition" and action.active != "": userName = action.sql_helper.query_username_by_userid(dc["botId"]) bg_config.post_single_config_to_backend({"type": "extra_info", "userName": userName, "configData": "--extraInfo-|activeAction|" + action.active}) flag, conditionList = action.query_post_action(dc) return str(1) if process_type in ["change_active", "delete_condition", "insert_condition", "update_condition"]: print "generate_all" # 先从数据库查询所有condition,再生成完整的action,最后提交完整的action flag, conditionList = action.query_post_action(dc) print flag return str(flag) elif flag == 2: # 插入condition时出现名字重复 return message return str(flag) elif request.method == "OPTIONS": return "do it" @app.route("/dataTransfer", methods=["GET", "OPTIONS"]) def data_transfer(): if request.method == "GET": botId = request.values.get("botId") botName = request.values.get("botName") action = Action() back = BackgroundConfig() actionStr, configStr = action.data_helper.query_data_by_id(botId) conditionSet = json.loads(actionStr) configSet = json.loads(configStr) conditionSet["botId"] = botId action.data_helper.insert_category_by_2id(conditionSet["botId"], 0, "默认") for condition in conditionSet["conditionList"]: condition["active"] = False for i in range(len(condition["repeatList"])): condition["repeatList"][i].update({"macro": ""}) condition["conditionCategory"] = "0:默认" newCondition = {"botId": botId, "conditionData": condition} action.insert_condition(newCondition) post_str = "" configSet["botId"] = botId for config in configSet["configList"]: nextStep = [] config["nextStepStatus"] = "return" config["nextStepList"] = [{}, ] config["nextStepList"][0]["nextStep"] = config["nextStep"] if config["nextStep"] != "" else " " config["nextStepList"][0]["except"] = [] nextStep.append(config["nextStep"]) newConfig = {"botId": botId, "configData": config, "categoryId": 0} flag, str = back.insert_config(newConfig) post_str += str + "\n" back.post_single_config_to_backend({"userName": botName, "configData": post_str, "configId": -1, "type": "batch_update"}) return "xx" if __name__ == '__main__': app.run(threaded=True, host="0.0.0.0", port=1111,)