-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·83 lines (64 loc) · 2.16 KB
/
server.py
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
#!/usr/bin/env python
from pymongo import MongoClient
import socket
import logging
import redis
import json
# add filemode="w" to overwrite
#logging.basicConfig(filename="/var/log/server.log", level=logging.INFO)
client = MongoClient(host='mongodb', port=27017)
db=client.mydb
coll = db.mycoll
sock = socket.socket()
sock.bind(('', 9091))
sock.listen(1)
conn, addr = sock.accept()
print ('connected:', addr)
cache = redis.Redis(host='rediska', port=6379)
cache.ping()
while True:
data = conn.recv(1024)
if not data:
break
response = { }
obj_data = {'action': 1 }
try:
obj_data = json.loads(data)
except ValueError as e:
response["Status"] = "Bad Request"
if obj_data["action"] == "get":
answ = cache.get(obj_data["key"])
if answ == None or obj_data["no-chache"]:
db_doc = coll.find_one({"key": obj_data["key"]})
if db_doc == None:
response["Status"] = "Not found"
else:
response["message"] = db_doc["msg"]
response["Status"] = "OK"
cache.set(obj_data["key"], response["message"]) #update chache
else:
if type(answ) is bytes:
response["message"] = answ.decode('utf-8')
else:
response["message"] = answ
response["Status"] = "OK"
print ('get:', response["message"])
if obj_data["action"] == "put":
if cache.exists(obj_data["key"]) :
response["Status"] = "Created"
else:
response["Status"] = "OK"
coll.insert_one({"key":obj_data["key"], "msg":obj_data["message"]})
#cache.set(obj_data["key"], obj_data["message"])
if obj_data["action"] == "delete":
db_doc = coll.find_one({"key": obj_data["key"]})
if db_doc != None :
coll.remove(db_doc)
cache.delete(obj_data["key"] )
response["Status"] = "OK"
else:
response["Status"] = "Not found"
json_string = json.dumps(response)
conn.send(json_string.encode('utf-8'))
#logging.info(data)
conn.close()