Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor: replace manual model_validate with @model_validate decorator in app controllers (#40170)

Likalikalid362bdbb4e05
diff --git a/api/controllers/console/app/agent_config_inspector.py b/api/controllers/console/app/agent_config_inspector.py
index 930dcd7814b..fe211db7218 100644
--- a/api/controllers/console/app/agent_config_inspector.py
+++ b/api/controllers/console/app/agent_config_inspector.py
@@ -30,6 +30,7 @@ from controllers.console.wraps import (
RBACResourceScope,
account_initialization_required,
edit_permission_required,
+ model_validate,
rbac_permission_required,
setup_required,
with_current_tenant_id,
@@ -810,14 +811,21 @@ class AgentConfigFilesByAgentApi(Resource):
@with_current_user
@with_current_tenant_id
@with_session
- def post(self, session: Session, tenant_id: str, current_user: Account, agent_id: UUID):
- payload = AgentConfigFileUploadPayload.model_validate(console_ns.payload or {})
+ @model_validate(AgentConfigFileUploadPayload)
+ def post(
+ self,
+ req_data: AgentConfigFileUploadPayload,
+ session: Session,
+ tenant_id: str,
+ current_user: Account,
+ agent_id: UUID,
+ ):
return _with_agent_route_target(
session=session,
tenant_id=tenant_id,
agent_id=agent_id,
current_user=current_user,
- action=lambda target: _file_upload_response(target, payload),
+ action=lambda target: _file_upload_response(target, req_data),
)
@@ -849,13 +857,13 @@ class AgentConfigFilesApi(Resource):
@with_current_user
@with_session
@get_app_model(mode=_WORKFLOW_APP_MODES)
- def post(self, session: Session, current_user: Account, app_model: App):
- payload = AgentConfigFileUploadPayload.model_validate(console_ns.payload or {})
+ @model_validate(AgentConfigFileUploadPayload)
+ def post(self, req_data: AgentConfigFileUploadPayload, session: Session, current_user: Account, app_model: App):
return _with_app_route_target(
session=session,
app_model=app_model,
current_user=current_user,
- action=lambda target: _file_upload_response(target, payload),
+ action=lambda target: _file_upload_response(target, req_data),
)
diff --git a/api/controllers/console/app/annotation.py b/api/controllers/console/app/annotation.py
index 6653a6e288c..dcad58593a0 100644
--- a/api/controllers/console/app/annotation.py
+++ b/api/controllers/console/app/annotation.py
@@ -20,6 +20,7 @@ from controllers.console.wraps import (
annotation_import_rate_limit,
cloud_edition_billing_resource_check,
edit_permission_required,
+ model_validate,
rbac_permission_required,
setup_required,
)
@@ -180,14 +181,14 @@ class AnnotationReplyActionApi(Resource):
@cloud_edition_billing_resource_check("annotation")
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
- def post(self, app_id: UUID, action: Literal["enable", "disable"]):
- args = AnnotationReplyPayload.model_validate(console_ns.payload)
+ @model_validate(AnnotationReplyPayload)
+ def post(self, req_data: AnnotationReplyPayload, app_id: UUID, action: Literal["enable", "disable"]):
match action:
case "enable":
enable_args: EnableAnnotationArgs = {
- "score_threshold": args.score_threshold,
- "embedding_provider_name": args.embedding_provider_name,
- "embedding_model_name": args.embedding_model_name,
+ "score_threshold": req_data.score_threshold,
+ "embedding_provider_name": req_data.embedding_provider_name,
+ "embedding_model_name": req_data.embedding_model_name,
}
result = AppAnnotationService.enable_app_annotation(enable_args, str(app_id))
case "disable":
@@ -231,12 +232,17 @@ class AppAnnotationSettingUpdateApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
@with_session
- def post(self, session: Session, app_id: UUID, annotation_setting_id: UUID):
+ @model_validate(AnnotationSettingUpdatePayload)
+ def post(
+ self,
+ req_data: AnnotationSettingUpdatePayload,
+ session: Session,
+ app_id: UUID,
+ annotation_setting_id: UUID,
+ ):
annotation_setting_id_str = str(annotation_setting_id)
- args = AnnotationSettingUpdatePayload.model_validate(console_ns.payload)
-
- setting_args: UpdateAnnotationSettingArgs = {"score_threshold": args.score_threshold}
+ setting_args: UpdateAnnotationSettingArgs = {"score_threshold": req_data.score_threshold}
result = AppAnnotationService.update_app_annotation_setting(
str(app_id), annotation_setting_id_str, setting_args, session
)
@@ -290,11 +296,11 @@ class AnnotationApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_VIEW_LAYOUT)
@with_session(write=False)
- def get(self, session: Session, app_id: UUID):
- args = AnnotationListQuery.model_validate(request.args.to_dict(flat=True))
- page = args.page
- limit = args.limit
- keyword = args.keyword
+ @model_validate(AnnotationListQuery)
+ def get(self, req_data: AnnotationListQuery, session: Session, app_id: UUID):
+ page = req_data.page
+ limit = req_data.limit
+ keyword = req_data.keyword
annotation_list, total = AppAnnotationService.get_annotation_list_by_app_id(
str(app_id), page, limit, keyword, session
@@ -317,17 +323,17 @@ class AnnotationApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
@with_session
- def post(self, session: Session, app_id: UUID):
- args = CreateAnnotationPayload.model_validate(console_ns.payload)
+ @model_validate(CreateAnnotationPayload)
+ def post(self, req_data: CreateAnnotationPayload, session: Session, app_id: UUID):
upsert_args: UpsertAnnotationArgs = {}
- if args.answer is not None:
- upsert_args["answer"] = args.answer
- if args.content is not None:
- upsert_args["content"] = args.content
- if args.message_id is not None:
- upsert_args["message_id"] = args.message_id
- if args.question is not None:
- upsert_args["question"] = args.question
+ if req_data.answer is not None:
+ upsert_args["answer"] = req_data.answer
+ if req_data.content is not None:
+ upsert_args["content"] = req_data.content
+ if req_data.message_id is not None:
+ upsert_args["message_id"] = req_data.message_id
+ if req_data.question is not None:
+ upsert_args["question"] = req_data.question
annotation = AppAnnotationService.up_insert_app_annotation_from_message(upsert_args, str(app_id), session)
return dump_response(Annotation, annotation), 201
@@ -407,13 +413,13 @@ class AnnotationUpdateDeleteApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_EDIT)
@with_session
- def post(self, session: Session, app_id: UUID, annotation_id: UUID):
- args = UpdateAnnotationPayload.model_validate(console_ns.payload)
+ @model_validate(UpdateAnnotationPayload)
+ def post(self, req_data: UpdateAnnotationPayload, session: Session, app_id: UUID, annotation_id: UUID):
update_args: UpdateAnnotationArgs = {}
- if args.answer is not None:
- update_args["answer"] = args.answer
- if args.question is not None:
- update_args["question"] = args.question
+ if req_data.answer is not None:
+ update_args["answer"] = req_data.answer
+ if req_data.question is not None:
+ update_args["question"] = req_data.question
app_ref = _get_app_ref(session, str(app_id))
annotation_ref = AppRefService.create_annotation_ref(app_ref, str(annotation_id))
annotation = AppAnnotationService.update_app_annotation_directly(update_args, annotation_ref, session)
diff --git a/api/controllers/console/app/ops_trace.py b/api/controllers/console/app/ops_trace.py
index e86f65fc035..2332f164cd9 100644
--- a/api/controllers/console/app/ops_trace.py
+++ b/api/controllers/console/app/ops_trace.py
@@ -1,6 +1,5 @@
from typing import Any
-from flask import request
from flask_restx import Resource
from pydantic import BaseModel, Field
from werkzeug.exceptions import BadRequest
@@ -14,6 +13,7 @@ from controllers.console.wraps import (
RBACResourceScope,
account_initialization_required,
edit_permission_required,
+ model_validate,
rbac_permission_required,
setup_required,
)
@@ -74,12 +74,11 @@ class TraceAppConfigApi(Resource):
@account_initialization_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TRACING_CONFIG)
@get_app_model
- def get(self, app_model: App):
- args = TraceProviderQuery.model_validate(request.args.to_dict(flat=True)) # type: ignore
-
+ @model_validate(TraceProviderQuery)
+ def get(self, req_data: TraceProviderQuery, app_model: App):
try:
trace_config = OpsService.get_tracing_app_config(
- app_id=app_model.id, tracing_provider=args.tracing_provider, session=db.session()
+ app_id=app_model.id, tracing_provider=req_data.tracing_provider, session=db.session()
)
if not trace_config:
return {"has_not_configured": True}
@@ -104,15 +103,14 @@ class TraceAppConfigApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TRACING_CONFIG)
@get_app_model
- def post(self, app_model: App):
+ @model_validate(TraceConfigPayload)
+ def post(self, req_data: TraceConfigPayload, app_model: App):
"""Create a new trace app configuration"""
- args = TraceConfigPayload.model_validate(console_ns.payload)
-
try:
result = OpsService.create_tracing_app_config(
app_id=app_model.id,
- tracing_provider=args.tracing_provider,
- tracing_config=args.tracing_config,
+ tracing_provider=req_data.tracing_provider,
+ tracing_config=req_data.tracing_config,
session=db.session(),
)
if not result:
@@ -140,15 +138,14 @@ class TraceAppConfigApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TRACING_CONFIG)
@get_app_model
- def patch(self, app_model: App):
+ @model_validate(TraceConfigPayload)
+ def patch(self, req_data: TraceConfigPayload, app_model: App):
"""Update an existing trace app configuration"""
- args = TraceConfigPayload.model_validate(console_ns.payload)
-
try:
result = OpsService.update_tracing_app_config(
app_id=app_model.id,
- tracing_provider=args.tracing_provider,
- tracing_config=args.tracing_config,
+ tracing_provider=req_data.tracing_provider,
+ tracing_config=req_data.tracing_config,
session=db.session(),
)
if not result:
@@ -170,13 +167,12 @@ class TraceAppConfigApi(Resource):
@edit_permission_required
@rbac_permission_required(RBACResourceScope.APP, RBACPermission.APP_TRACING_CONFIG)
@get_app_model
- def delete(self, app_model: App):
+ @model_validate(TraceProviderQuery)
+ def delete(self, req_data: TraceProviderQuery, app_model: App):
"""Delete an existing trace app configuration"""
- args = TraceProviderQuery.model_validate(request.args.to_dict(flat=True))
-
try:
result = OpsService.delete_tracing_app_config(
- app_id=app_model.id, tracing_provider=args.tracing_provider, session=db.session()
+ app_id=app_model.id, tracing_provider=req_data.tracing_provider, session=db.session()
)
if not result:
raise TracingConfigNotExist()
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
index f7ed936ee74..d21d0e2618a 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_config_inspector.py
@@ -8,7 +8,7 @@ from __future__ import annotations
from inspect import unwrap
from types import SimpleNamespace
-from unittest.mock import MagicMock, PropertyMock, patch
+from unittest.mock import MagicMock, patch
from flask import Flask
from sqlalchemy import event
@@ -28,7 +28,6 @@ from controllers.console.app.agent_config_inspector import (
AgentConfigSkillInspectByAgentApi,
AgentConfigSkillsApi,
AgentConfigSkillUploadByAgentApi,
- console_ns,
)
from services.agent_config_service import AgentConfigServiceError
@@ -212,13 +211,10 @@ def test_skill_upload_by_agent_delegates_after_version_resolution():
def test_file_upload_by_agent_delegates_to_service_owned_upload_lookup():
raw = _raw(AgentConfigFilesByAgentApi.post)
- with app.test_request_context("/?draft_type=debug_build"):
+ with app.test_request_context("/?draft_type=debug_build", json={"upload_file_id": "upload-1"}):
with (
patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
patch(f"{_MOD}.AgentComposerService") as composer,
- patch.object(
- type(console_ns), "payload", new_callable=PropertyMock, return_value={"upload_file_id": "upload-1"}
- ),
patch(f"{_MOD}.AgentConfigService") as config_service,
):
composer.load_agent_app_build_draft.return_value = {"draft": {"id": "build-draft-1"}}
@@ -226,7 +222,14 @@ def test_file_upload_by_agent_delegates_to_service_owned_upload_lookup():
"file": {"id": "guide.txt", "name": "guide.txt", "file_id": "upload-1"},
"config_version": {"id": "build-draft-1", "kind": "build_draft", "writable": True},
}
- body, status = raw(AgentConfigFilesByAgentApi(), MagicMock(), "tenant-1", _USER, "agent-1")
+ body, status = raw(
+ AgentConfigFilesByAgentApi(),
+ inspector.AgentConfigFileUploadPayload(upload_file_id="upload-1"),
+ MagicMock(),
+ "tenant-1",
+ _USER,
+ "agent-1",
+ )
assert status == 201
assert body["file"]["name"] == "guide.txt"
assert config_service.return_value.push_file_for_console.call_args.kwargs["upload_file_id"] == "upload-1"
diff --git a/api/tests/unit_tests/controllers/console/app/test_annotation_api.py b/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
index f225ef73477..028e5005583 100644
--- a/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_annotation_api.py
@@ -163,12 +163,10 @@ class TestConsoleAnnotationRefBoundaries:
api = annotation_module.AnnotationUpdateDeleteApi()
handler = unwrap(api.post)
update_mock = Mock(return_value=_annotation_model())
- payload = {"question": "updated"}
_persist_app(sqlite_session)
with (
- app.test_request_context("/annotations/ann-1", method="POST", json=payload),
- patch.object(type(annotation_module.console_ns), "payload", payload),
+ app.test_request_context("/annotations/ann-1", method="POST", json={"question": "updated"}),
patch.object(
annotation_module,
"current_account_with_tenant",
@@ -176,7 +174,13 @@ class TestConsoleAnnotationRefBoundaries:
),
patch.object(annotation_module.AppAnnotationService, "update_app_annotation_directly", update_mock),
):
- response = handler(api, sqlite_session, "app-1", "ann-1")
+ response = handler(
+ api,
+ annotation_module.UpdateAnnotationPayload(question="updated"),
+ sqlite_session,
+ "app-1",
+ "ann-1",
+ )
assert response["question"] == "q"
update_mock.assert_called_once()
diff --git a/api/tests/unit_tests/controllers/console/app/test_app_apis.py b/api/tests/unit_tests/controllers/console/app/test_app_apis.py
index 2b428ad1f12..5aa4ae92467 100644
--- a/api/tests/unit_tests/controllers/console/app/test_app_apis.py
+++ b/api/tests/unit_tests/controllers/console/app/test_app_apis.py
@@ -301,7 +301,7 @@ class TestOpsTraceEndpoints:
)
with app.test_request_context("/?tracing_provider=langfuse"):
- result = method(api, app_model=MagicMock(id="app-1"))
+ result = method(api, TraceProviderQuery(tracing_provider="langfuse"), MagicMock(id="app-1"))
assert result == {"has_not_configured": True}
@@ -320,7 +320,11 @@ class TestOpsTraceEndpoints:
json={"tracing_provider": "langfuse", "tracing_config": {"api_key": "k"}},
):
with pytest.raises(BadRequest):
- method(api, app_model=MagicMock(id="app-1"))
+ method(
+ api,
+ TraceConfigPayload(tracing_provider="langfuse", tracing_config={"api_key": "k"}),
+ MagicMock(id="app-1"),
+ )
def test_trace_app_config_delete_not_found(self, app: Flask, monkeypatch: pytest.MonkeyPatch):
api = ops_trace_module.TraceAppConfigApi()
@@ -334,7 +338,7 @@ class TestOpsTraceEndpoints:
with app.test_request_context("/?tracing_provider=langfuse"):
with pytest.raises(BadRequest):
- method(api, app_model=MagicMock(id="app-1"))
+ method(api, TraceProviderQuery(tracing_provider="langfuse"), MagicMock(id="app-1"))
class TestSiteEndpoints: