Spaces:
Sleeping
Sleeping
add mongodb log
Browse files- mongo_lib.py +38 -0
mongo_lib.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#python -m pip install "pymongo[srv]==3.11"
|
| 2 |
+
from pymongo.mongo_client import MongoClient
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
def insert_mongodb_log(model_name,document:dict):
|
| 7 |
+
|
| 8 |
+
mongo_uri = os.getenv('mongo_uri')
|
| 9 |
+
client = MongoClient(mongo_uri)
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
#client.admin.command('ping')
|
| 13 |
+
# 選擇數據庫,如果不存在會自動創建
|
| 14 |
+
db = client["huggingface-space"] # 替換成你想要的數據庫名稱
|
| 15 |
+
# 選擇集合,如果不存在會自動創建
|
| 16 |
+
collection = db["space-log"] # 替換成你想要的集合名稱
|
| 17 |
+
# 將文檔插入到集合中
|
| 18 |
+
document.update({"model_name":model_name,"process_time": str(datetime.now())})
|
| 19 |
+
|
| 20 |
+
result = collection.insert_one(document)
|
| 21 |
+
# 打印插入結果
|
| 22 |
+
#print(f"Document inserted with ID: {result.inserted_id}")
|
| 23 |
+
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(e)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if __name__ == "__main__":
|
| 30 |
+
# 創建JSON文檔
|
| 31 |
+
document = {
|
| 32 |
+
"msg": "hello world",
|
| 33 |
+
"status": "success",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
insert_mongodb_log("test_client",document)
|
| 37 |
+
|
| 38 |
+
|