-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdatabase.py
More file actions
109 lines (92 loc) · 3.13 KB
/
database.py
File metadata and controls
109 lines (92 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : database.py
@Author : Racle
@Version : 1.0
@Desc : None
'''
# 由于FAQ问题,数据集比较小,可以储存在redis数据库。
import redis
class RedisDb:
def __init__(self, host, password, max_connections):
try:
self.__pool = redis.ConnectionPool(
host=host,
port=6379,
password=password,
db=0,
max_connections=max_connections
)
except Exception as e:
print(e)
def insert(self, id, question, answer):
connection = redis.Redis(connection_pool=self.__pool)
try:
connection.hmset(id, {
"question": question,
"answer": answer
})
except Exception as e:
print(e)
finally:
del connection
def search_by_id(self, id):
connection = redis.Redis(connection_pool=self.__pool)
try:
res = connection.hmget(id, [
"question",
"answer"
])
except Exception as e:
print(e)
res = [None, None]
finally:
del connection
return res
def delete_cache(self, id):
connection = redis.Redis(connection_pool=self.__pool)
try:
connection.delete(id)
except Exception as e:
print(e)
finally:
del connection
#########################################################################
### 持久化储存对话记录
#########################################################################
from pymongo import MongoClient
from bson.objectid import ObjectId
class MongoDb:
def __init__(self, host, username, password):
self.__client = MongoClient(host=host, port=27017)
self.__client.admin.authenticate(username, password)
def insert(self, question, answer):
try:
self.__client['bank_record']['conversation'].insert_one({"question": question,
"answer": answer})
except Exception as e:
print(e)
def search_id(self, question):
try:
news = self.__client['bank_record']['conversation'].find_one({"question": question})
return str(news["_id"])
except Exception as e:
print(e)
def update(self, id, question, answer):
try:
self.__client['bank_record']['conversation'].update_one({"_id": ObjectId(id)},
{"$set": {"question": question, "answer": answer}})
except Exception as e:
print(e)
def search_answer_by_id(self, id):
try:
news = self.__client['bank_record']['conversation'].find_one({"_id": ObjectId(id)})
return news["answer"]
except Exception as e:
print(e)
def delete_by_id(self, id):
try:
self.__client['bank_record']['conversation'].delete_one({"_id": ObjectId(id)})
except Exception as e:
print(e)