選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

search_app.py 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from flask import request
  17. from flask_login import current_user, login_required
  18. from api import settings
  19. from api.constants import DATASET_NAME_LIMIT
  20. from api.db import StatusEnum
  21. from api.db.db_models import DB
  22. from api.db.services import duplicate_name
  23. from api.db.services.search_service import SearchService
  24. from api.db.services.user_service import TenantService, UserTenantService
  25. from api.utils import get_uuid
  26. from api.utils.api_utils import get_data_error_result, get_json_result, not_allowed_parameters, server_error_response, validate_request
  27. @manager.route("/create", methods=["post"]) # noqa: F821
  28. @login_required
  29. @validate_request("name")
  30. def create():
  31. req = request.get_json()
  32. search_name = req["name"]
  33. description = req.get("description", "")
  34. if not isinstance(search_name, str):
  35. return get_data_error_result(message="Search name must be string.")
  36. if search_name.strip() == "":
  37. return get_data_error_result(message="Search name can't be empty.")
  38. if len(search_name.encode("utf-8")) > 255:
  39. return get_data_error_result(message=f"Search name length is {len(search_name)} which is large than 255.")
  40. e, _ = TenantService.get_by_id(current_user.id)
  41. if not e:
  42. return get_data_error_result(message="Authorizationd identity.")
  43. search_name = search_name.strip()
  44. search_name = duplicate_name(SearchService.query, name=search_name, tenant_id=current_user.id, status=StatusEnum.VALID.value)
  45. req["id"] = get_uuid()
  46. req["name"] = search_name
  47. req["description"] = description
  48. req["tenant_id"] = current_user.id
  49. req["created_by"] = current_user.id
  50. with DB.atomic():
  51. try:
  52. if not SearchService.save(**req):
  53. return get_data_error_result()
  54. return get_json_result(data={"search_id": req["id"]})
  55. except Exception as e:
  56. return server_error_response(e)
  57. @manager.route("/update", methods=["post"]) # noqa: F821
  58. @login_required
  59. @validate_request("search_id", "name", "search_config", "tenant_id")
  60. @not_allowed_parameters("id", "created_by", "create_time", "update_time", "create_date", "update_date", "created_by")
  61. def update():
  62. req = request.get_json()
  63. if not isinstance(req["name"], str):
  64. return get_data_error_result(message="Search name must be string.")
  65. if req["name"].strip() == "":
  66. return get_data_error_result(message="Search name can't be empty.")
  67. if len(req["name"].encode("utf-8")) > DATASET_NAME_LIMIT:
  68. return get_data_error_result(message=f"Search name length is {len(req['name'])} which is large than {DATASET_NAME_LIMIT}")
  69. req["name"] = req["name"].strip()
  70. tenant_id = req["tenant_id"]
  71. e, _ = TenantService.get_by_id(tenant_id)
  72. if not e:
  73. return get_data_error_result(message="Authorizationd identity.")
  74. search_id = req["search_id"]
  75. if not SearchService.accessible4deletion(search_id, current_user.id):
  76. return get_json_result(data=False, message="No authorization.", code=settings.RetCode.AUTHENTICATION_ERROR)
  77. try:
  78. search_app = SearchService.query(tenant_id=tenant_id, id=search_id)[0]
  79. if not search_app:
  80. return get_json_result(data=False, message=f"Cannot find search {search_id}", code=settings.RetCode.DATA_ERROR)
  81. if req["name"].lower() != search_app.name.lower() and len(SearchService.query(name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value)) >= 1:
  82. return get_data_error_result(message="Duplicated search name.")
  83. if "search_config" in req:
  84. current_config = search_app.search_config or {}
  85. new_config = req["search_config"]
  86. if not isinstance(new_config, dict):
  87. return get_data_error_result(message="search_config must be a JSON object")
  88. updated_config = {**current_config, **new_config}
  89. req["search_config"] = updated_config
  90. req.pop("search_id", None)
  91. req.pop("tenant_id", None)
  92. updated = SearchService.update_by_id(search_id, req)
  93. if not updated:
  94. return get_data_error_result(message="Failed to update search")
  95. e, updated_search = SearchService.get_by_id(search_id)
  96. if not e:
  97. return get_data_error_result(message="Failed to fetch updated search")
  98. return get_json_result(data=updated_search.to_dict())
  99. except Exception as e:
  100. return server_error_response(e)
  101. @manager.route("/detail", methods=["GET"]) # noqa: F821
  102. @login_required
  103. def detail():
  104. search_id = request.args["search_id"]
  105. try:
  106. tenants = UserTenantService.query(user_id=current_user.id)
  107. for tenant in tenants:
  108. if SearchService.query(tenant_id=tenant.tenant_id, id=search_id):
  109. break
  110. else:
  111. return get_json_result(data=False, message="Has no permission for this operation.", code=settings.RetCode.OPERATING_ERROR)
  112. search = SearchService.get_detail(search_id)
  113. if not search:
  114. return get_data_error_result(message="Can't find this Search App!")
  115. return get_json_result(data=search)
  116. except Exception as e:
  117. return server_error_response(e)
  118. @manager.route("/list", methods=["POST"]) # noqa: F821
  119. @login_required
  120. def list_search_app():
  121. keywords = request.args.get("keywords", "")
  122. page_number = int(request.args.get("page", 0))
  123. items_per_page = int(request.args.get("page_size", 0))
  124. orderby = request.args.get("orderby", "create_time")
  125. if request.args.get("desc", "true").lower() == "false":
  126. desc = False
  127. else:
  128. desc = True
  129. req = request.get_json()
  130. owner_ids = req.get("owner_ids", [])
  131. try:
  132. if not owner_ids:
  133. tenants = TenantService.get_joined_tenants_by_user_id(current_user.id)
  134. tenants = [m["tenant_id"] for m in tenants]
  135. search_apps, total = SearchService.get_by_tenant_ids(tenants, current_user.id, page_number, items_per_page, orderby, desc, keywords)
  136. else:
  137. tenants = owner_ids
  138. search_apps, total = SearchService.get_by_tenant_ids(tenants, current_user.id, 0, 0, orderby, desc, keywords)
  139. search_apps = [search_app for search_app in search_apps if search_app["tenant_id"] in tenants]
  140. total = len(search_apps)
  141. if page_number and items_per_page:
  142. search_apps = search_apps[(page_number - 1) * items_per_page : page_number * items_per_page]
  143. return get_json_result(data={"search_apps": search_apps, "total": total})
  144. except Exception as e:
  145. return server_error_response(e)
  146. @manager.route("/rm", methods=["post"]) # noqa: F821
  147. @login_required
  148. @validate_request("search_id")
  149. def rm():
  150. req = request.get_json()
  151. search_id = req["search_id"]
  152. if not SearchService.accessible4deletion(search_id, current_user.id):
  153. return get_json_result(data=False, message="No authorization.", code=settings.RetCode.AUTHENTICATION_ERROR)
  154. try:
  155. if not SearchService.delete_by_id(search_id):
  156. return get_data_error_result(message=f"Failed to delete search App {search_id}")
  157. return get_json_result(data=True)
  158. except Exception as e:
  159. return server_error_response(e)