瀏覽代碼

数据库连接test

22285461@qq.com 6 月之前
父節點
當前提交
8f825a65ab
共有 1 個文件被更改,包括 15 次插入1 次删除
  1. 15 1
      main.py

+ 15 - 1
main.py

@@ -296,6 +296,20 @@ async def test(request: Request):
     request_origin = request.headers.get('origin')
     if request_origin is None:
         request_origin = "unknown"
-    content = {"message": "Hello World" + request_origin}
+    content = {"message": "Hello World" + request_origin, "db": "disconnect"}
     headers = {'Access-Control-Allow-Origin': request_origin}
+    try:
+        database.connect(reuse_if_open=True)
+        dt = CustomUser.select()
+        for item in dt:
+            print(item.id)
+        content["db"] = "connected"
+    except OperationalError as e:
+        if 'MySQL server has gone away' in str(e):
+            content["db"] = "broke"
+            database.close()
+            database.connect()
+            if database.is_connected():
+                content["db"] = "broke , reconnect"
+            logging.info("reconnect database")
     return JSONResponse(content=content, headers=headers)