Przeglądaj źródła

update DaoDaoBackend

刘清 2 miesięcy temu
rodzic
commit
4b8a67dc5a
31 zmienionych plików z 10215 dodań i 30 usunięć
  1. 43
    4
      DaoDaoBackend/StartBackend.py
  2. BIN
      DaoDaoBackend/__pycache__/StartBackend.cpython-311.pyc
  3. BIN
      DaoDaoBackend/app/__pycache__/__init__.cpython-311.pyc
  4. BIN
      DaoDaoBackend/app/__pycache__/app.cpython-311.pyc
  5. 3
    1
      DaoDaoBackend/app/api/v1/__init__.py
  6. BIN
      DaoDaoBackend/app/api/v1/__pycache__/__init__.cpython-311.pyc
  7. BIN
      DaoDaoBackend/app/api/v1/__pycache__/book.cpython-311.pyc
  8. BIN
      DaoDaoBackend/app/api/v1/__pycache__/chatMsg.cpython-311.pyc
  9. BIN
      DaoDaoBackend/app/api/v1/__pycache__/user.cpython-311.pyc
  10. BIN
      DaoDaoBackend/app/api/v1/__pycache__/video.cpython-311.pyc
  11. 134
    0
      DaoDaoBackend/app/api/v1/chatMsg.py
  12. 135
    18
      DaoDaoBackend/app/api/v1/user.py
  13. 113
    0
      DaoDaoBackend/app/api/v1/video.py
  14. 20
    5
      DaoDaoBackend/app/app.py
  15. BIN
      DaoDaoBackend/app/config/__pycache__/secure.cpython-311.pyc
  16. BIN
      DaoDaoBackend/app/config/__pycache__/setting.cpython-311.pyc
  17. 12
    2
      DaoDaoBackend/app/config/setting.py
  18. BIN
      DaoDaoBackend/app/libs/__pycache__/redprint.cpython-311.pyc
  19. BIN
      DaoDaoBackend/gunicorn/__pycache__/gunicorn.conf.cpython-311.pyc
  20. 14
    0
      DaoDaoBackend/gunicorn/gunicorn.conf.py
  21. 1
    0
      DaoDaoBackend/gunicorn/gunicorn.pid
  22. 4794
    0
      DaoDaoBackend/gunicorn/gunicorn_acess.log
  23. 4745
    0
      DaoDaoBackend/gunicorn/gunicorn_error.log
  24. 4
    0
      DaoDaoBackend/gunicorn/readme
  25. 19
    0
      DaoDaoBackend/other/CreatUniqueIndex.py
  26. 37
    0
      DaoDaoBackend/other/InitUserInfo.py
  27. 38
    0
      DaoDaoBackend/other/InitVideoInfo.py
  28. 40
    0
      DaoDaoBackend/other/InsertVideo.py
  29. 20
    0
      DaoDaoBackend/other/testSocketIo.py
  30. 35
    0
      DaoDaoBackend/readme
  31. 8
    0
      DaoDaoBackend/run.log

+ 43
- 4
DaoDaoBackend/StartBackend.py Wyświetl plik

@@ -1,11 +1,50 @@
1 1
 
2 2
 from app.app import create_app
3
-#前面app指的是项目文件夹app,后面app指的是app文件夹下面的初始化文件__init__.py中创建的实例,实例名app
3
+from flask_socketio import SocketIO, emit
4
+from werkzeug.middleware.proxy_fix import ProxyFix
5
+from app.app import mongo
6
+
4 7
  
5 8
 app = create_app()
6
-#print(app)
7
- 
9
+# print(app)
10
+
11
+
12
+app.wsgi_app = ProxyFix(
13
+    app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1
14
+)
15
+
16
+# 初始化SocketIO
17
+socketio = SocketIO(app, cors_allowed_origins="*")
18
+
19
+
20
+# 定义集合
21
+rooms_collection = {
22
+    "all": mongo.db.chatAll,  # 所有人聊天
23
+    "one2one": mongo.db.chatOne2One,  # 一对一聊天
24
+    "more2more": mongo.db.chatMore2More  # 多对多聊天
25
+}
26
+
27
+@socketio.on('message')
28
+def handle_message(data):
29
+    print(data)
30
+    room_id = data["roomId"]
31
+    if room_id in rooms_collection:
32
+        collection = rooms_collection[room_id]
33
+        collection.insert_one(data)
34
+        
35
+        response_event = f'responseMsg_{room_id}'
36
+        # broadcast_flag = room_id != 'one2one'
37
+        broadcast_flag = True
38
+
39
+        if '_id' in data:
40
+            del data['_id']
41
+        emit(response_event, data, broadcast=broadcast_flag)
42
+    else:
43
+        print(f"Unsupported room: {room_id}")
44
+
45
+
8 46
 if __name__ == '__main__':
9 47
     #app.run(debug=True)#若调试,可考虑开启debug模式,修改代码后服务自动重启,使修改生效,方便调试,生产环境
10
-	app.run(host="0.0.0.0", port=5569, debug=True)
48
+	# app.run(host="0.0.0.0", port=5569, debug=True)
49
+    socketio.run(app, host="0.0.0.0", port=5569, debug=True)  # 使用 socketio.run 替换 app.run
11 50
 	

BIN
DaoDaoBackend/__pycache__/StartBackend.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/__pycache__/__init__.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/__pycache__/app.cpython-311.pyc Wyświetl plik


+ 3
- 1
DaoDaoBackend/app/api/v1/__init__.py Wyświetl plik

@@ -1,6 +1,6 @@
1 1
  
2 2
 from flask import Blueprint
3
-from app.api.v1 import user, book
3
+from app.api.v1 import user, book, chatMsg, video
4 4
  
5 5
  
6 6
 def create_blueprint_v1():
@@ -9,4 +9,6 @@ def create_blueprint_v1():
9 9
     # 将红图注册到蓝图当中
10 10
     user.api.register(bp_v1)
11 11
     book.api.register(bp_v1)
12
+    chatMsg.api.register(bp_v1)
13
+    video.api.register(bp_v1)
12 14
     return bp_v1

BIN
DaoDaoBackend/app/api/v1/__pycache__/__init__.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/api/v1/__pycache__/book.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/api/v1/__pycache__/chatMsg.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/api/v1/__pycache__/user.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/api/v1/__pycache__/video.cpython-311.pyc Wyświetl plik


+ 134
- 0
DaoDaoBackend/app/api/v1/chatMsg.py Wyświetl plik

@@ -0,0 +1,134 @@
1
+from app.app import mongo
2
+from app.libs.redprint import Redprint
3
+from flask import jsonify, request
4
+from bson.objectid import ObjectId
5
+from pymongo.errors import PyMongoError
6
+import traceback
7
+
8
+api = Redprint('chatMsg')
9
+
10
+
11
+@api.route('/get/all')
12
+def get_all_msg():
13
+    # mongo.db.chatAll.delete_many({})
14
+    msg_infos = list(mongo.db.chatAll.find())
15
+    for msg_info in msg_infos:
16
+        msg_info["_id"] = str(msg_info["_id"])
17
+    return jsonify(msg_infos)
18
+
19
+
20
+@api.route('/get/one2one/<sendId>/<rspId>')
21
+def get_o2o_msg(sendId, rspId):
22
+    # mongo.db.chatOne2One.delete_many({})
23
+    msg_infos = list(mongo.db.chatOne2One.find())
24
+    # 使用列表推导式过滤掉 resUserId 等于 chaterId 的元素
25
+    msg_infos = [msg_info for msg_info in msg_infos if (sendId == msg_info["sendUserId"] and rspId == msg_info["resUserId"] or rspId == msg_info["sendUserId"] and sendId == msg_info["resUserId"])]
26
+
27
+    for msg_info in msg_infos:
28
+        msg_info["_id"] = str(msg_info["_id"])
29
+
30
+    return jsonify(msg_infos)
31
+
32
+
33
+@api.route('/get/more2more')
34
+def get_m2m_msg():
35
+    msg_infos = list(mongo.db.chatMore2More.find())
36
+    for msg_info in msg_infos:
37
+        msg_info["_id"] = str(msg_info["_id"])
38
+    return jsonify(msg_infos)
39
+
40
+
41
+def InitItem(item, id):
42
+    user_id_obj = ObjectId(id)
43
+    user = mongo.db.users.find_one({"_id": user_id_obj})
44
+    if user:
45
+        item["userId"] = id
46
+        item["username"] = user["username"]
47
+        item["avatar"] = user["avatar_url"]
48
+        item["lastMsgContent"] = "您有一条新信息..."
49
+        item["time"] = "2024-09-18 12:36:09"
50
+        item["unreadCount"] = 1
51
+
52
+
53
+@api.route('/get/chatItems/<user_id>')
54
+def get_msg_list(user_id):
55
+    user_id_obj = ObjectId(user_id)  # 尝试将user_id转化为ObjectId
56
+    # mongo.db.chatList.delete_many({})
57
+    try:
58
+        # 从chatUsers数组中找到对应的用户聊天信息
59
+        result = mongo.db.chatList.find_one(
60
+            {"userId": user_id_obj},
61
+        )
62
+    except Exception as e:
63
+        return jsonify({"message": f"Database error: {str(e)}"}), 500
64
+
65
+    if result is None:
66
+        # 文档未找到或用户未找到,返回 404 和提示信息
67
+        return jsonify({"message": f"Chat items for user {user_id} do not exist."}), 404
68
+
69
+    # 从结果中提取用户的聊天列表
70
+    user_chat_info_ids = result.get('chatUsers', [])
71
+
72
+    user_chat_list_info = []
73
+    for user_chat_info_id in user_chat_info_ids:
74
+        item = {}
75
+        InitItem(item, user_chat_info_id)
76
+        user_chat_list_info.append(item)
77
+
78
+    # 返回数组
79
+    return jsonify(user_chat_list_info), 200
80
+
81
+
82
+@api.route('/appendChatUser', methods=['POST'])
83
+def append_msg_list():
84
+    data = request.get_json()
85
+
86
+    user_id = data["userId"]
87
+    to_append_id = data["id"]
88
+
89
+    # 将字符串形式的user_id转换为ObjectId
90
+    user_id_obj = ObjectId(user_id)
91
+
92
+    try:
93
+        # 使用update_one,如果文档存在则更新,不存在则插入
94
+        result = mongo.db.chatList.update_one(
95
+            {"userId": user_id_obj},
96
+            {
97
+                "$addToSet": {"chatUsers": to_append_id},
98
+                "$setOnInsert": {"userId": user_id_obj}
99
+            },
100
+            upsert=True
101
+        )
102
+        
103
+        if result.matched_count > 0:
104
+            return jsonify({"message": "ID added successfully to existing user."}), 201
105
+        else:
106
+            return jsonify({"message": "New user created and ID added."}), 201
107
+    
108
+    except PyMongoError as e:
109
+        return jsonify({"error": f"Database error: {str(e)}", "traceback": traceback.format_exc()}), 500
110
+
111
+# id: obj.a2bId,
112
+# name: obj.username,
113
+# avatarList: obj.avatar,
114
+# note: obj.lastMsgContent,
115
+# time: obj.time,
116
+# unreadCount: obj.unreadCount
117
+
118
+
119
+# {
120
+#     {
121
+#       "userId": ObjectId("61d679a12e4d4e348a103c79"),
122
+#       "chatUsers": [
123
+#         ObjectId("61d679a12e4d4e348a103c7a"),
124
+#         ObjectId("61d679a12e4d4e348a103c7b")
125
+#       ]
126
+#     },
127
+#     {
128
+#       "userId": ObjectId("61d679a12e4d4e348a103c7c"),
129
+#       "chatUsers": [
130
+#         ObjectId("61d679a12e4d4e348a103c7a"),
131
+#         ObjectId("61d679a12e4d4e348a103c7d")
132
+#       ]
133
+#     }
134
+# }

+ 135
- 18
DaoDaoBackend/app/api/v1/user.py Wyświetl plik

@@ -1,41 +1,158 @@
1 1
 #user.py
2 2
  
3 3
 from app.libs.redprint import Redprint
4
-from app.app import db
5 4
 from flask import jsonify, request
5
+from app.app import mongo
6
+from app.app import jwt
7
+from bson.json_util import dumps
8
+from bson.objectid import ObjectId
9
+from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
10
+import bcrypt
11
+from pymongo.errors import DuplicateKeyError
12
+from werkzeug.exceptions import BadRequest
6 13
  
7 14
 # 初始化红图
8 15
 api = Redprint('user')
9
- 
16
+
10 17
  
11 18
 @api.route('/get')
12 19
 def get_user2():
13 20
     return "I am user get method"
14
- 
15
- 
16
-@api.route('/create', methods=['POST'])
17
-def get_create_user():
18
-	user_info = request.get_json()
19
-	result = db.users.insert_one(user_info)
20
-    return jsonify({"_id": str(result.inserted_id)})
21
+
22
+
23
+def check_password(username, password):
24
+    # 找到用户
25
+    user = mongo.db.users.find_one({"username": username})
26
+    if user is None:
27
+        # 返回一个更泛化的错误信息
28
+        return {"error": "此用户名不存在."}, 404
29
+    # 验证密码
30
+    if bcrypt.checkpw(password.encode('utf-8'), user['password_hash']):
31
+        return {"message": "Password correct"}, 200
32
+    else:
33
+        return {"error": "密码错误."}, 401
34
+        
35
+
36
+def make_jwt_info(user):
37
+    # 使用flask_jwt_extended的create_access_token函数创建JWT
38
+    access_token = create_access_token(identity=str(user['_id']), additional_claims={
39
+        'email': user['email'],
40
+        'username': user['username'],
41
+        'avatar_url': user['avatar_url'],
42
+        'bio': user['bio']
43
+    })
44
+    return access_token
45
+
46
+
47
+@api.route('/pwdlogin', methods=['POST'])
48
+def user_pwd_login():
49
+    username = request.json.get('username')
50
+    password = request.json.get('password')
51
+    result, status_code = check_password(username, password)  # 解包元组
52
+    # 根据check_password的返回结果处理
53
+    if result.get('message') == "Password correct":
54
+        # access_token = create_access_token(identity=username)
55
+        user = mongo.db.users.find_one({"username": username})
56
+        access_token = make_jwt_info(user)
57
+        return jsonify({'token': access_token}), 200
58
+    else:
59
+        return jsonify(result), status_code  # 使用从check_password返回的状态码
60
+
61
+
62
+def InitUserInfo(user_info):
63
+    user_info["avatar_url"] = "https://afanai.top:8088/imgs/default_avatar_1.jpeg"
64
+    user_info["bio"] = "永远不要降低心灵飞翔的高度"
65
+    user_info["password_hash"] = bcrypt.hashpw(user_info["password"].encode('utf-8'), bcrypt.gensalt())
66
+
67
+
68
+@api.route('/register', methods=['POST'])
69
+def user_pwd_register():
70
+    user_info = request.get_json()
71
+    InitUserInfo(user_info)
72
+    try:
73
+        mongo.db.users.insert_one(user_info)
74
+        username = user_info["username"]
75
+        return jsonify({"message": f"User {username} registered successfully."}), 201
76
+    except DuplicateKeyError as e:
77
+        # 处理DuplicateKeyError
78
+        # 从异常信息中解析出冲突的字段
79
+        error_message = str(e)
80
+        if 'username' in error_message:
81
+            return jsonify({"error": "此用户名已存在."}), 409
82
+        if 'email' in error_message:
83
+            return jsonify({"error": "此邮箱已被注册."}), 409
84
+        # 如果异常信息中没有明确的字段信息,可以考虑更详细的异常处理或日志记录
85
+        return jsonify({"error": "未知错误."}), 500
21 86
 	
22 87
 	
23 88
 @api.route('/getall')
24 89
 def get_all_user():
25
-	user_infos = list(db.users.find())
26
-	# 将ObjectId转换为字符串,以便于JSON序列化
27
-	for user_info in user_infos:
28
-		user_info['_id'] = str(user_info['_id'])
29
-	return jsonify(user_infos)
90
+    user_infos = list(mongo.db.users.find())
91
+    # 将ObjectId转换为字符串,以便于JSON序列化
92
+    # 使用bson的json_util来序列化包含ObjectId的对象
93
+    # json_string = dumps(user_infos)
94
+    for user_info in user_infos:
95
+        user_info["_id"] = str(user_info["_id"])
96
+        user_info["password_hash"] = "******"
97
+    return jsonify(user_infos)
30 98
 	
31 99
 	
32 100
 @api.route('/modify/<user_id>', methods=['PUT'])
33
-def get_all_user(user_id):
34
-	item = request.get_json()
35
-	result = db.users.update_one({"_id": ObjectId(user_id)}, {"$set": item})
36
-	return jsonify({"modified_count": result.modified_count})
101
+def modify_specify_user(user_id):
102
+    try:
103
+        item = request.get_json()
104
+        # print(item)
105
+        if not item:
106
+            raise BadRequest("请求体为空")
107
+        # 将user_id转换为ObjectId
108
+        user_id_obj = ObjectId(user_id)
109
+        result = mongo.db.users.update_one({"_id": user_id_obj}, {"$set": item})
110
+        # 如果没有找到或修改任何文档
111
+        if result.modified_count == 0:
112
+            return jsonify({"error": "未找到用户或没有数据被修改"}), 404
113
+        
114
+        user = mongo.db.users.find_one({"_id": user_id_obj})
115
+        access_token = make_jwt_info(user)
116
+        return jsonify({'token': access_token}), 201
117
+    except BadRequest as e:
118
+        return jsonify({"error": str(e)}), 400
119
+    except Exception as e:
120
+        return jsonify({"error": "内部服务器错误"}), 500
37 121
 	
38 122
 
123
+@api.route('/search', methods=['GET'])
124
+def search_specify_user():
125
+    try:
126
+        # 从查询字符串中获取参数
127
+        query = request.args.get('query')
128
+        print(query)
129
+        if not query:
130
+            raise BadRequest("查询参数为空")
131
+
132
+        # 搜索用户名
133
+        user = mongo.db.users.find_one({"username": query})
134
+        # print(user)
135
+        queryUser = {}
136
+        queryRes = []
137
+        if user:
138
+            queryUser["userId"] = str(user["_id"])
139
+            queryUser["username"] = user["username"]
140
+            queryUser["avatar_url"] = user["avatar_url"]
141
+            queryUser["bio"] = user["bio"]
142
+            queryRes.append(queryUser)
143
+        print(queryRes)
144
+
145
+        if len(queryRes):
146
+            return jsonify({'queryRes': queryRes}), 200
147
+        else:
148
+            return jsonify({'queryRes': "None Result"}), 404
149
+        
150
+    except BadRequest as e:
151
+        return jsonify({"error": str(e)}), 400
152
+    except Exception as e:
153
+        return jsonify({"error": "内部服务器错误"}), 500
154
+
155
+
39 156
 # @api.route('/items', methods=['POST'])
40 157
 # def add_item():
41 158
 #     item = request.get_json()

+ 113
- 0
DaoDaoBackend/app/api/v1/video.py Wyświetl plik

@@ -0,0 +1,113 @@
1
+#video.py
2
+ 
3
+from app.libs.redprint import Redprint
4
+from flask import jsonify, request
5
+from app.app import mongo
6
+from app.app import jwt
7
+from bson.json_util import dumps
8
+from bson.objectid import ObjectId
9
+from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
10
+import bcrypt
11
+import re
12
+from pymongo.errors import DuplicateKeyError
13
+from werkzeug.exceptions import BadRequest
14
+ 
15
+# 初始化红图
16
+api = Redprint('video')
17
+
18
+ 
19
+@api.route('/get')
20
+def get_video():
21
+    return "I am video get method"
22
+
23
+
24
+@api.route('/getall')
25
+def get_all_video():
26
+    video_infos = list(mongo.db.videos.find())
27
+    # 将ObjectId转换为字符串,以便于JSON序列化
28
+    # 使用bson的json_util来序列化包含ObjectId的对象
29
+    # json_string = dumps(user_infos)
30
+    for video_info in video_infos:
31
+        video_info["_id"] = str(video_info["_id"])
32
+    return jsonify(video_infos)
33
+
34
+
35
+@api.route('/getBlobUrl', methods=['GET'])
36
+def get_blob_url_video():
37
+    try:
38
+        # 从查询字符串中获取参数
39
+        query = ObjectId(request.args.get('query'))
40
+        print(query)
41
+        
42
+        if not query:
43
+            raise BadRequest("查询参数为空")
44
+        
45
+        video = mongo.db.videos.find_one({"_id": query})
46
+        if video:
47
+            bolb_url = video["video_url"]
48
+            print(bolb_url)
49
+
50
+        if bolb_url:
51
+            return jsonify({'queryRes': bolb_url}), 200
52
+        else:
53
+            return jsonify({'queryRes': "None Result"}), 404
54
+        
55
+    except BadRequest as e:
56
+        return jsonify({"error": str(e)}), 400
57
+    except Exception as e:
58
+        return jsonify({"error": "内部服务器错误"}), 500
59
+
60
+
61
+@api.route('/search', methods=['GET'])
62
+def search_specify_video():
63
+    try:
64
+        # 从查询字符串中获取参数
65
+        query = request.args.get('query')
66
+        print(query)
67
+        if not query:
68
+            raise BadRequest("查询参数为空")
69
+        
70
+
71
+        # 搜索视频 如果由#开头则搜索id,否则搜索视频名称
72
+        video = {}
73
+        videos = []
74
+        if query[0] == '#' :
75
+            if (query == "#1000001#") :
76
+                videos = mongo.db.videos.find()
77
+            else:
78
+                video = mongo.db.videos.find_one({"video_id": query})
79
+        else :
80
+            paQuery = {"video_name": {"$regex": query, "$options": "i"}}
81
+            videos = mongo.db.videos.find(paQuery)
82
+        
83
+        # queryVideo = {}
84
+        queryRes = []
85
+        if video:
86
+            queryVideo = {}
87
+            queryVideo["duration"] = video["duration"]
88
+            queryVideo["cover_url"] = video["cover_url"]
89
+            queryVideo["video_name"] = video["video_name"]
90
+            queryVideo["uploader_id"] = video["uploader_id"]
91
+            # queryVideo["video_url"] = video["video_url"]
92
+            queryVideo["video_id"] = str(video["_id"])
93
+            queryRes.append(queryVideo)
94
+        
95
+        for videoItem in videos:
96
+            queryVideo = {}
97
+            queryVideo["duration"] = videoItem["duration"]
98
+            queryVideo["cover_url"] = videoItem["cover_url"]
99
+            queryVideo["video_name"] = videoItem["video_name"]
100
+            queryVideo["uploader_id"] = videoItem["uploader_id"]
101
+            # queryVideo["video_url"] = video["video_url"]
102
+            queryVideo["video_id"] = str(videoItem["_id"])
103
+            queryRes.append(queryVideo)
104
+
105
+        if len(queryRes):
106
+            return jsonify({'queryRes': queryRes}), 200
107
+        else:
108
+            return jsonify({'queryRes': "None Result"}), 200
109
+        
110
+    except BadRequest as e:
111
+        return jsonify({"error": str(e)}), 400
112
+    except Exception as e:
113
+        return jsonify({"error": "内部服务器错误"}), 500

+ 20
- 5
DaoDaoBackend/app/app.py Wyświetl plik

@@ -1,6 +1,13 @@
1 1
 from flask import Flask
2 2
 from pymongo import MongoClient
3
- 
3
+from flask_pymongo import PyMongo
4
+from flask_jwt_extended import JWTManager
5
+from flask_cors import CORS
6
+
7
+
8
+mongo = PyMongo()
9
+jwt = JWTManager()
10
+
4 11
  
5 12
 def register_blueprints(app):
6 13
     from app.api.v1 import create_blueprint_v1
@@ -11,10 +18,18 @@ def create_app():
11 18
     app = Flask(__name__)
12 19
     app.config.from_object('app.config.setting')
13 20
     app.config.from_object('app.config.secure')
14
-	
15
-	# 初始化MongoDB连接
16
-	app.db = MongoClient(app.config['MONGO_URI']).get_database(app.config['MONGO_DBNAME'])
17
-	
21
+    
22
+    # 初始化MongoDB连接
23
+    #app.db = MongoClient(app.config['MONGO_URI']).get_database(app.config['MONGO_DBNAME'])
24
+    mongo.init_app(app)
25
+    jwt.init_app(app)
26
+
27
+    
28
+    # 初始化 CORS,允许所有源访问, 调试解决跨域问题,项目完成后删除
29
+    CORS(app)
30
+
31
+    # app.config['JSON_AS_ASCLL'] = False
32
+    
18 33
     # 将蓝图注册到app 上
19 34
     register_blueprints(app)
20 35
     return app

BIN
DaoDaoBackend/app/config/__pycache__/secure.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/app/config/__pycache__/setting.cpython-311.pyc Wyświetl plik


+ 12
- 2
DaoDaoBackend/app/config/setting.py Wyświetl plik

@@ -1,6 +1,16 @@
1 1
 # app/config/setting.py
2 2
 #MONGO_URI = 'mongodb://username:password@host:port'
3 3
 #MONGO_DBNAME = 'your_db_name'
4
+#MONGODB_SETTINGS = {
5
+#    'db': 'your_db_name',
6
+#    'host': 'your_db_host',
7
+#    'port': 27017,
8
+#    'username': 'your_db_username',
9
+#    'password': 'your_db_password',
10
+#}
4 11
 
5
-MONGO_URI = 'mongodb://127.0.0.1:27017/'
6
-MONGO_DBNAME = 'starter_db'
12
+MONGO_URI = 'mongodb://127.0.0.1:27017/starter_db'
13
+MONGO_DBNAME = 'starter_db'
14
+JSON_AS_ASCII = False
15
+
16
+JWT_SECRET_KEY = 'heweidabangzi77!'

BIN
DaoDaoBackend/app/libs/__pycache__/redprint.cpython-311.pyc Wyświetl plik


BIN
DaoDaoBackend/gunicorn/__pycache__/gunicorn.conf.cpython-311.pyc Wyświetl plik


+ 14
- 0
DaoDaoBackend/gunicorn/gunicorn.conf.py Wyświetl plik

@@ -0,0 +1,14 @@
1
+import multiprocessing
2
+
3
+bind = '127.0.0.1:5569' #要绑定的socket(配置nginx后,需要把0.0.0.0改为127.0.0.1)
4
+#workers = multiprocessing.cpu_count() * 2 + 1 #处理请求的工作进程数,官方推荐(2 * cpu核数 + 1)
5
+workers = 1
6
+reload = True #代码改变后自动重启工作进程
7
+worker_class = 'eventlet' #工作进程的类型,分别是sync, eventlet, gevent, tornado, gthread
8
+#threads = 2 #工作类型为gthread时才生效
9
+worker_connections = 1000 #默认1000,每个worker同时处理的最大客户端连接数,gthread\eventlet\gevent模式生效
10
+pidfile = './gunicorn/gunicorn.pid' #进程文件目录,不设置就没有进程文件
11
+accesslog = './gunicorn/gunicorn_acess.log' #访问日志路径
12
+errorlog = './gunicorn/gunicorn_error.log' #错误信息日志路径
13
+loglevel = 'warning' #错误日志级别,'debug'\'info'\'warning'\'error'\'critical'
14
+daemon = True #在后台运行

+ 1
- 0
DaoDaoBackend/gunicorn/gunicorn.pid Wyświetl plik

@@ -0,0 +1 @@
1
+429506

+ 4794
- 0
DaoDaoBackend/gunicorn/gunicorn_acess.log
Plik diff jest za duży
Wyświetl plik


+ 4745
- 0
DaoDaoBackend/gunicorn/gunicorn_error.log
Plik diff jest za duży
Wyświetl plik


+ 4
- 0
DaoDaoBackend/gunicorn/readme Wyświetl plik

@@ -0,0 +1,4 @@
1
+���������ļ� gunicorn -c gunicorn.conf.py hello:app
2
+�鿴 pid ��kill����
3
+
4
+(starter_env) root@debian:/usr/environments/StartBackend# gunicorn -c ./gunicorn/gunicorn.conf.py StartBackend:app

+ 19
- 0
DaoDaoBackend/other/CreatUniqueIndex.py Wyświetl plik

@@ -0,0 +1,19 @@
1
+# coding: utf-8
2
+from pymongo import MongoClient
3
+
4
+# MongoDB的连接信息
5
+MONGO_URI = 'mongodb://127.0.0.1:27017'
6
+MONGO_DBNAME = 'starter_db'
7
+
8
+# 创建MongoDB的连接
9
+client = MongoClient(MONGO_URI)
10
+
11
+# 选择或创建数据库
12
+db = client[MONGO_DBNAME]
13
+
14
+# 选择或创建集合(类似关系数据库中的表)
15
+users_collection = db['users']
16
+
17
+# 创建唯一索引
18
+users_collection.create_index('username', unique=True)
19
+users_collection.create_index('email', unique=True)

+ 37
- 0
DaoDaoBackend/other/InitUserInfo.py Wyświetl plik

@@ -0,0 +1,37 @@
1
+# coding: utf-8
2
+from pymongo import MongoClient
3
+import bcrypt
4
+
5
+# MongoDB的连接信息
6
+MONGO_URI = 'mongodb://127.0.0.1:27017'
7
+MONGO_DBNAME = 'starter_db'
8
+
9
+# 创建MongoDB的连接
10
+client = MongoClient(MONGO_URI)
11
+
12
+# 选择或创建数据库
13
+db = client[MONGO_DBNAME]
14
+
15
+# 选择或创建集合(类似关系数据库中的表)
16
+users_collection = db['users']
17
+
18
+# 清空集合,如果集合已经存在并有数据
19
+users_collection.delete_many({})
20
+
21
+
22
+# 插入一些示例数据
23
+sample_users = [
24
+    {"username": "developuser", "email": "developuser@example.com", "avatar_url": "https://afanai.top:8088/imgs/default_avatar_1.jpeg", "bio": "This account is for develop", "password_hash": bcrypt.hashpw("super123".encode('utf-8'), bcrypt.gensalt())}
25
+]
26
+
27
+for i in sample_users:
28
+    print(i)
29
+
30
+# 执行插入操作
31
+result = users_collection.insert_many(sample_users)
32
+
33
+# 打印插入的文档ID
34
+print("Inserted document IDs:", result.inserted_ids)
35
+
36
+# 关闭数据库连接
37
+client.close()

+ 38
- 0
DaoDaoBackend/other/InitVideoInfo.py Wyświetl plik

@@ -0,0 +1,38 @@
1
+# coding: utf-8
2
+from pymongo import MongoClient
3
+import bcrypt
4
+
5
+# MongoDB的连接信息
6
+MONGO_URI = 'mongodb://127.0.0.1:27017'
7
+MONGO_DBNAME = 'starter_db'
8
+
9
+# 创建MongoDB的连接
10
+client = MongoClient(MONGO_URI)
11
+
12
+# 选择或创建数据库
13
+db = client[MONGO_DBNAME]
14
+
15
+# 选择或创建集合(类似关系数据库中的表)
16
+users_collection = db['videos']
17
+
18
+# 清空集合,如果集合已经存在并有数据
19
+users_collection.delete_many({})
20
+
21
+
22
+# 插入一些示例数据
23
+sample_video = [
24
+    {"video_id": "#00000", "duration": "65", "cover_url": "https://afanai.top:8088/video/982789760frame.jpg", "video_name": "鞠婧祎视频1", "uploader_id": "00001", "video_url": "https://afanai.top:8088/video/982789760.mp4"},
25
+    {"video_id": "#00001", "duration": "65", "cover_url": "https://afanai.top:8088/video/428743782frame.jpg", "video_name": "鞠婧祎视频2", "uploader_id": "00001", "video_url": "https://afanai.top:8088/video/428743782.mp4"}
26
+]
27
+
28
+for i in sample_video:
29
+    print(i)
30
+
31
+# 执行插入操作
32
+result = users_collection.insert_many(sample_video)
33
+
34
+# 打印插入的文档ID
35
+print("Inserted document IDs:", result.inserted_ids)
36
+
37
+# 关闭数据库连接
38
+client.close()

+ 40
- 0
DaoDaoBackend/other/InsertVideo.py Wyświetl plik

@@ -0,0 +1,40 @@
1
+# coding: utf-8
2
+from pymongo import MongoClient
3
+import bcrypt
4
+
5
+# MongoDB的连接信息
6
+MONGO_URI = 'mongodb://127.0.0.1:27017'
7
+MONGO_DBNAME = 'starter_db'
8
+
9
+# 创建MongoDB的连接
10
+client = MongoClient(MONGO_URI)
11
+
12
+# 选择或创建数据库
13
+db = client[MONGO_DBNAME]
14
+
15
+# 选择或创建集合(类似关系数据库中的表)
16
+users_collection = db['videos']
17
+
18
+# 清空集合,如果集合已经存在并有数据
19
+# users_collection.delete_many({})
20
+
21
+
22
+# 插入一些示例数据
23
+sample_video = [
24
+    {"video_id": "#70007", "duration": "65", "cover_url": "https://afanai.top:8088/video/567645453frame.jpg", "video_name": "hp_0", "uploader_id": "00001", "video_url": "https://afanai.top:8088/video/567645453.mp4"}
25
+    # {"video_id": "#00001", "duration": "65", "cover_url": "https://afanai.top:8088/video/428743782frame.jpg", "video_name": "鞠婧祎视频2", "uploader_id": "00001", "video_url": "https://afanai.top:8088/video/428743782.mp4"}
26
+]
27
+
28
+for i in sample_video:
29
+    print(i)
30
+
31
+# 执行插入操作
32
+result = users_collection.insert_many(sample_video)
33
+# result = users_collection.insert_one(sample_video)
34
+
35
+
36
+# 打印插入的文档ID
37
+print("Inserted document IDs:", result.inserted_ids)
38
+
39
+# 关闭数据库连接
40
+client.close()

+ 20
- 0
DaoDaoBackend/other/testSocketIo.py Wyświetl plik

@@ -0,0 +1,20 @@
1
+from flask import Flask
2
+from flask_socketio import SocketIO, emit
3
+from flask_cors import CORS
4
+
5
+app = Flask(__name__)
6
+
7
+# 初始化CORS,允许所有源
8
+CORS(app, cors_allowed_origins="*")  # 显式指定所有资源允许所有源
9
+
10
+socketio = SocketIO(app, cors_allowed_origins="*")  # SocketIO也允许所有源
11
+
12
+@socketio.on('message')
13
+def handle_message(data):
14
+    # print('received message: ' + str(data))
15
+    if not data.roomId == "all":
16
+        return
17
+    emit('responseMsg', data, broadcast=True)
18
+
19
+if __name__ == '__main__':
20
+    socketio.run(app, host="0.0.0.0", port=8089, debug=True)

+ 35
- 0
DaoDaoBackend/readme Wyświetl plik

@@ -0,0 +1,35 @@
1
+/my_flask_app
2
+│
3
+├── app/                # 主要的 Flask 应用代码目录
4
+│   ├── __init__.py     # 初始化 Flask 应用
5
+│   ├── config.py       # 配置文件
6
+│   ├── api/            # API 蓝图目录
7
+│   │   ├── __init__.py 
8
+│   │   └── v1/         # v1 版本的 API
9
+│   │       ├── __init__.py
10
+│   │       └── endpoints.py
11
+│   ├── models.py       # 数据模型
12
+│   └── views.py        # 视图函数
13
+│
14
+├── socketio/           # SocketIO 相关代码的目录
15
+│   ├── __init__.py     # 初始化 SocketIO
16
+│   └── events.py       # SocketIO 事件处理器
17
+│
18
+├── requirements.txt    # 项目依赖
19
+├── manage.py           # 主启动文件
20
+│
21
+└── README.md           # 项目说明文件
22
+
23
+
24
+�ӿ�˵��
25
+
26
+1. �û����
27
+  1.1 �û��������¼
28
+    https://ip:port/v1/user/pwdlogin
29
+  1.2 �û�ע��
30
+    https://ip:port/v1/user/register
31
+
32
+
33
+run 
34
+  1. 切换到虚拟环境 source ../starter_env/bin/activate
35
+  2. 运行python 

+ 8
- 0
DaoDaoBackend/run.log Wyświetl plik

@@ -0,0 +1,8 @@
1
+nohup: ignoring input
2
+Traceback (most recent call last):
3
+  File "/usr/environments/StartBackend/StartBackend.py", line 31, in <module>
4
+    socketio.run(app, host="0.0.0.0", port=5569, debug=True)  # 使用 socketio.run 替换 app.run
5
+    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6
+  File "/usr/environments/starter_env/lib/python3.11/site-packages/flask_socketio/__init__.py", line 646, in run
7
+    raise RuntimeError('The Werkzeug web server is not '
8
+RuntimeError: The Werkzeug web server is not designed to run in production. Pass allow_unsafe_werkzeug=True to the run() method to disable this error.