-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclean_expired_sessions.py
46 lines (37 loc) · 1.18 KB
/
clean_expired_sessions.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
#!/usr/bin/python3
import pymongo
import datetime
import os
import re
username = os.getenv('MONGODB_USER')
password = os.getenv('MONGODB_PASSWORD')
db_name = os.getenv('DB')
host = os.getenv('MONGODB_HOST')
port = os.getenv('MONGODB_PORT')
expiration = os.getenv('SESSION_EXPIRATION')
print(f"Current time: {datetime.datetime.now()}")
try:
if username is None or username == '':
mongodb = "mongodb://" + host + ':' + port + "/"
else:
mongodb = "mongodb://" + username + ':' + password + '@' + host + ':' + port + "/"
except TypeError:
print("请先配置MongoDB连接地址!")
client = pymongo.MongoClient(mongodb)
db = client[db_name]
col = db["session"]
days = re.compile(r'\d+d',re.I)
hours = re.compile(r'\d+h',re.I)
num = re.compile(r'\d+')
now = datetime.datetime.today()
if days.search(expiration) is None:
d = 0
else:
d = int(num.search(days.search(expiration).group(0)).group(0))
if hours.search(expiration) is None:
h = 0
else:
h = int(num.search(hours.search(expiration).group(0)).group(0))
query = {"expiration": {"$lt": (now - datetime.timedelta(days=d,hours=h))}}
n = col.delete_many(query)
print(n.deleted_count, "个session(s)已清理")