import web,os.path,requests,random,sqlite3,datetime,json urls = ( '/(.*)', 'index' ) def create_db(): # 在数据库中存储 BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sqlite3_path = os.path.join(BASE_DIR, 'ChatWithoutMoodQuestionnaire', 'chatmessage.sqlite3') return sqlite3_path def customhook(): web.header('Access-Control-Allow-Origin', '*') web.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST') web.header('Access-Control-Allow-Headers', 'content-type') web.header('content-type', 'application/json') web.header("Access-Control-Allow-Credentials", "true") class index: def GET(self, name): if not name: name = 'World' return 'Hello, ' + name + '!' def POST(self,data): text=web.input().text #url: 机器人接口地址 url = 'http://openapi.tuling123.com/openapi/api/v2' radom_list=[1,5,4,3] radom_str=random.choice(radom_list) if radom_str==2 : answer = {'text':'抱歉,我听不懂你的问题'} else: data_param = { "reqType": 0, "perception": { "inputText": { "text": text }, "inputImage": { "url": "imageUrl" }, "selfInfo": { "location": { "city": "郑州", "province": "河南", "street": "12222" } } }, "userInfo": { "apiKey": "a677fd9cff8a4228b702e9bd717c5e7f", "userId": "1" } } response = requests.post(url=url, json=data_param) py_json = response.text py_dict = json.loads(py_json) results_list = py_dict['results'] results_0_dict = results_list[0] values_dict = results_0_dict['values'] answer = values_dict session = web.input().session ip = web.ctx.env['REMOTE_ADDR'] createtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') question = text sql_path=create_db() con = sqlite3.connect(sql_path) cur = con.cursor() sql = "insert into chatmessage ('session','question','ip','answer','createtime') VALUES ('%s','%s','%s','%s','%s')"%(session,question,ip,answer['text'],createtime) cur.execute(sql) con.commit() con.close() return json.dumps({'replay_text': answer}) if __name__ == "__main__": app = web.application(urls, globals()) app.add_processor(web.loadhook(customhook)) app.run() # # python serverChat.py 192.168.0.104:4000