Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: 应用、知识库、函数库增加创建者 #1546

Merged
merged 1 commit into from
Nov 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions apps/application/serializers/application_serializers.py
Original file line number Diff line number Diff line change
@@ -19,8 +19,10 @@
from django.contrib.postgres.fields import ArrayField
from django.core import cache, validators
from django.core import signing
from django.core.paginator import Paginator
from django.db import transaction, models
from django.db.models import QuerySet
from django.db.models import QuerySet, Q
from django.forms import CharField
from django.http import HttpResponse
from django.template import Template, Context
from rest_framework import serializers
@@ -44,7 +46,7 @@
from dataset.serializers.common_serializers import list_paragraph, get_embedding_model_by_dataset_id_list
from embedding.models import SearchMode
from function_lib.serializers.function_lib_serializer import FunctionLibSerializer
from setting.models import AuthOperate
from setting.models import AuthOperate, TeamMember, TeamMemberPermission
from setting.models.model_management import Model
from setting.models_provider import get_model_credential
from setting.models_provider.constants.model_provider_constants import ModelProvideConstants
@@ -559,17 +561,22 @@ class Query(serializers.Serializer):
desc = serializers.CharField(required=False, error_messages=ErrMessage.char("应用描述"))

user_id = serializers.UUIDField(required=True, error_messages=ErrMessage.uuid("用户id"))
select_user_id = serializers.UUIDField(required=False, error_messages=ErrMessage.uuid("选择用户id"))

def get_query_set(self):
user_id = self.data.get("user_id")
query_set_dict = {}
query_set = QuerySet(model=get_dynamics_model(
{'temp_application.name': models.CharField(), 'temp_application.desc': models.CharField(),
'temp_application.create_time': models.DateTimeField()}))
'temp_application.create_time': models.DateTimeField(),
'temp_application.user_id': models.CharField(), }))
if "desc" in self.data and self.data.get('desc') is not None:
query_set = query_set.filter(**{'temp_application.desc__icontains': self.data.get("desc")})
if "name" in self.data and self.data.get('name') is not None:
query_set = query_set.filter(**{'temp_application.name__icontains': self.data.get("name")})
if 'select_user_id' in self.data and self.data.get('select_user_id') is not None and self.data.get(
'select_user_id') != 'all':
query_set = query_set.filter(**{'temp_application.user_id__exact': self.data.get('select_user_id')})
query_set = query_set.order_by("-temp_application.create_time")
query_set_dict['default_sql'] = query_set

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个问题看起来是在关于Django的REST框架和ModelViewSet中的一种模型操作类。根据您的问题描述,似乎在调用query_set_dict之前没有给出具体的操作指令或参数。

对于优化建议,这里有几个点可以考虑改进:

  1. 确保您理解了提供的数据结构和业务逻辑。
  2. 使用更详细的错误信息来帮助调试可能存在的bug。
  3. 在实际编程开发过程中尽量遵循可读性和清晰性的原则(例如使用注释、格式化代码等)以提高维护性。

如果您需要具体的解决方案,请提供更多细节。

6 changes: 5 additions & 1 deletion apps/dataset/serializers/dataset_serializers.py
Original file line number Diff line number Diff line change
@@ -129,17 +129,21 @@ class Query(ApiMixin, serializers.Serializer):
)

user_id = serializers.CharField(required=True)
select_user_id = serializers.CharField(required=False)

def get_query_set(self):
user_id = self.data.get("user_id")
query_set_dict = {}
query_set = QuerySet(model=get_dynamics_model(
{'temp.name': models.CharField(), 'temp.desc': models.CharField(),
"document_temp.char_length": models.IntegerField(), 'temp.create_time': models.DateTimeField()}))
"document_temp.char_length": models.IntegerField(), 'temp.create_time': models.DateTimeField(),
'temp.user_id': models.CharField(), }))
if "desc" in self.data and self.data.get('desc') is not None:
query_set = query_set.filter(**{'temp.desc__icontains': self.data.get("desc")})
if "name" in self.data and self.data.get('name') is not None:
query_set = query_set.filter(**{'temp.name__icontains': self.data.get("name")})
if "select_user_id" in self.data and self.data.get('select_user_id') is not None:
query_set = query_set.filter(**{'temp.user_id__exact': self.data.get("select_user_id")})
query_set = query_set.order_by("-temp.create_time")
query_set_dict['default_sql'] = query_set

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个API类在Python中的实现和当前日期(2024年11月5日)之间存在差异。

  1. 对于QuerySet, temp.id应该使用model.field_name来获取模型字段,而不是'id'
  2. 在查询时添加了self.data.get('desc') in Noneself.data.get('name') in None的判断语句会更加简洁。这样不会引发TypeError。
  3. 如果需要指定用户ID,则可以设置get()方法为False,以忽略query选项。例如
if "select_user_id" in self.data:
        if self.data['select_user_id']:
            query_set = query_set.filter(**{'temp.user_id__exact': self.data.get('select_user_id')})

这样就避免了不必要的检查。
以上就是在给定上下文信息的基础上我能够发现的所有潜在问题,当然实际运行中可能还有其他未被我发现的问题,请提供具体的业务场景以便分析更深入的情况。

2 changes: 1 addition & 1 deletion apps/dataset/views/dataset.py
Original file line number Diff line number Diff line change
@@ -221,7 +221,7 @@ class Page(APIView):
def get(self, request: Request, current_page, page_size):
d = DataSetSerializers.Query(
data={'name': request.query_params.get('name', None), 'desc': request.query_params.get("desc", None),
'user_id': str(request.user.id)})
'user_id': str(request.user.id), 'select_user_id': request.query_params.get('select_user_id', None)})
d.is_valid()
return result.success(d.page(current_page, page_size))

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个代码没有明显的错误或问题,但是有一些小的变化:

def get(self, request: Request, current_page: int, page_size: int):
        d = DataSetSerializers.Query(
            data={'name': request.query_params.get('name', None), 'desc': request.query_params.get("desc", None),
                    'user_id': str(request.user.id)})  

更改为:

      self.serializer_class = DataSetSerializers

在类上方添加 import datasets 这一行来处理数据集。

由于你只是询问关于是否有必要改进或优化该段代码以达到更好的质量,请提出你的意见。

3 changes: 3 additions & 0 deletions apps/function_lib/serializers/function_lib_serializer.py
Original file line number Diff line number Diff line change
@@ -98,6 +98,7 @@ class Query(serializers.Serializer):
is_active = serializers.BooleanField(required=False, error_messages=ErrMessage.char("是否可用"))

user_id = serializers.UUIDField(required=True, error_messages=ErrMessage.uuid("用户id"))
select_user_id = serializers.CharField(required=False, allow_null=True, allow_blank=True)

def get_query_set(self):
query_set = QuerySet(FunctionLib).filter(
@@ -108,6 +109,8 @@ def get_query_set(self):
query_set = query_set.filter(desc__contains=self.data.get('desc'))
if self.data.get('is_active') is not None:
query_set = query_set.filter(is_active=self.data.get('is_active'))
if self.data.get('select_user_id') is not None:
query_set = query_set.filter(user_id=self.data.get('select_user_id'))
query_set = query_set.order_by("-create_time")
return query_set

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这段代码存在一些可能需要改善的地方。以下是修改后的版本:

  1. 修改serializers.UUIDField
  2. allow_null=Trueallow_blank=True放在get_query_set方法中,这将确保字段值为 None" " 时仍可以返回查询集。

请注意,以上更改仅是针对您的问题进行的具体修改。如果您有任何其他疑问或想要我提供进一步帮助,请随时告诉我。

3 changes: 2 additions & 1 deletion apps/function_lib/views/function_lib_views.py
Original file line number Diff line number Diff line change
@@ -105,5 +105,6 @@ def get(self, request: Request, current_page: int, page_size: int):
FunctionLibSerializer.Query(
data={'name': request.query_params.get('name'),
'desc': request.query_params.get('desc'),
'user_id': request.user.id}).page(
'user_id': request.user.id,
'select_user_id': request.query_params.get('select_user_id')}).page(
current_page, page_size))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

该代码可能存在以下问题:

  1. 查询字符串应该使用双引号,例如:'name=%s', 使用占位符 %s 将参数设置为实际数据。

  2. 函数名可能需要更清晰地表示其目的:

        @get
    
  3. 参数名称应遵循 Python 的命名约定(下划线命名)以提高可读性。

37 changes: 36 additions & 1 deletion apps/users/serializers/user_serializers.py
Original file line number Diff line number Diff line change
@@ -17,7 +17,7 @@
from django.core.mail import send_mail
from django.core.mail.backends.smtp import EmailBackend
from django.db import transaction
from django.db.models import Q, QuerySet
from django.db.models import Q, QuerySet, Prefetch
from drf_yasg import openapi
from rest_framework import serializers

@@ -35,6 +35,7 @@
from common.util.lock import lock
from dataset.models import DataSet, Document, Paragraph, Problem, ProblemParagraphMapping
from embedding.task import delete_embedding_by_dataset_id_list
from function_lib.models.function import FunctionLib
from setting.models import Team, SystemSetting, SettingType, Model, TeamMember, TeamMemberPermission
from smartdoc.conf import PROJECT_DIR
from users.models.user import User, password_encrypt, get_user_dynamics_permission
@@ -495,6 +496,40 @@ def list(self, with_valid=True):
return [{'id': user_model.id, 'username': user_model.username, 'email': user_model.email} for user_model in
QuerySet(User).filter(Q(username=email_or_username) | Q(email=email_or_username))]

def listByType(self, type, user_id):
teamIds = TeamMember.objects.filter(user_id=user_id).values_list('id', flat=True)
targets = TeamMemberPermission.objects.filter(
member_id__in=teamIds,
auth_target_type=type,
operate__contains=['USE']
).values_list('target', flat=True)
prefetch_users = Prefetch('user', queryset=User.objects.only('id', 'username'))

user_list = []
if type == 'DATASET':
user_list = DataSet.objects.filter(
Q(id__in=targets) | Q(user_id=user_id)
).prefetch_related(prefetch_users).distinct('user_id')
elif type == 'APPLICATION':
user_list = Application.objects.filter(
Q(id__in=targets) | Q(user_id=user_id)
).prefetch_related(prefetch_users).distinct('user_id')
elif type == 'FUNCTION':
user_list = FunctionLib.objects.filter(
Q(permission_type='PUBLIC') | Q(user_id=user_id)
).prefetch_related(prefetch_users).distinct('user_id')

other_users = [
{'id': app.user.id, 'username': app.user.username}
for app in user_list if app.user.id != user_id
]
users = [
{'id': 'all', 'username': '全部'},
{'id': user_id, 'username': '我的'}
]
users.extend(other_users)
return users


class UserInstanceSerializer(ApiMixin, serializers.ModelSerializer):
class Meta:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个文档的主要任务是为一个名为UserModel的django模型创建序列化器。它首先定义了一个方法来获取符合条件或用户ID的成员列表和权限查询集,然后根据类型(数据集,应用,函数)从这些对象中提取出指定用户的用户名,并构建一组包含所有可用用户的字符串列表。

在代码格式上并没有什么大问题,但有一个小建议:可以将other_users = []移到另一个行,避免多次使用相同的变量名,这样更整洁一些。另外,如果要增加更多的字段到serializer,只需要重新定义类即可。

1 change: 1 addition & 0 deletions apps/users/urls.py
Original file line number Diff line number Diff line change
@@ -21,4 +21,5 @@
name="user_manage_re_password"),
path("user_manage/<int:current_page>/<int:page_size>", views.UserManage.Page.as_view(),
name="user_manage_re_password"),
path('user/list/<str:type>', views.UserListView.as_view()),
]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个代码已经很紧凑,没有什么明显的风格问题或功能缺失。以下是几点可能需要改进的地方:

  1. 如果用户在后台修改密码后想重新登录,请考虑引入一个路由 views.user_manage_re_login 来处理这个逻辑。

  2. 在使用URL字符串时,应该注意一些特殊情况和约束条件。

  3. 调整 user_manage/re_password/ 链接的路径名称到 user/manage/password/re 以反映更清楚的内容。

这是关于细节方面的优化调整,整体上代码没有明显缺陷或需要特别关注的部分。

13 changes: 13 additions & 0 deletions apps/users/views/user.py
Original file line number Diff line number Diff line change
@@ -301,3 +301,16 @@ def get(self, request: Request, user_id):
def put(self, request: Request, user_id):
return result.success(
UserManageSerializer.Operate(data={'id': user_id}).edit(request.data, with_valid=True))


class UserListView(APIView):
authentication_classes = [TokenAuth]

@swagger_auto_schema(operation_summary="通过类型获取用户列表",
operation_id="通过类型获取用户列表",
manual_parameters=UserSerializer.Query.get_request_params_api(),
responses=result.get_api_array_response(UserSerializer.Query.get_response_body_api()),
tags=['用户'])
@has_permissions(PermissionConstants.USER_READ)
def get(self, request: Request, type):
return result.success(UserSerializer().listByType(type, request.user.id))
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个问题需要进一步分析,因为没有直接给出问题或修改需求。请问您在讨论的是哪个具体的代码片段呢?

另外,请提供上下文背景信息以及实际的代码实现,以便于更准确地进行评估和建议。

请注意,以下建议可能需要更多的详细信息才能有效:

  1. 如果您的问题是关于Python编程语言中的语法错误,请使用pylint 或者其他静态代码分析工具对程序进行格式化,并根据提示查找并修复可能存在的问题。
  2. 对于常见的编码风格问题(如缩进),您可以尝试按照PEP8指南来重新写代码使其更加易于维护和读取。
  3. 考虑将逻辑合并到一个函数中以提高封装性;考虑是否可以使用ORM简化查询数据。
  4. 审视API接口文档的更新情况:如果某个参数被移除了或定义不同了,这可能会引起意外的结果。

10 changes: 9 additions & 1 deletion ui/src/api/application.ts
Original file line number Diff line number Diff line change
@@ -456,6 +456,13 @@ const putWorkFlowVersion: (
)
}

const getUserList: (type: string, loading?: Ref<boolean>) => Promise<Result<any>> = (
type,
loading
) => {
return get(`/user/list/${type}`, undefined, loading)
}

export default {
getAllAppilcation,
getApplication,
@@ -492,5 +499,6 @@ export default {
getWorkFlowVersion,
getWorkFlowVersionDetail,
putWorkFlowVersion,
playDemoText
playDemoText,
getUserList
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

我无法查看代码中的差异,因为我没有权限访问特定的应用或API。我可以为您提供一些建议来改进给定的代码:

  • 确保你的类型和参数列表与请求一致

  • 尽可能地将复杂的操作分解成更小的功能模块,避免复杂性和维护性问题。

如果你需要帮助检查具体的差异,请提供你想要比较的具体代码片段。

20 changes: 15 additions & 5 deletions ui/src/components/card-box/index.vue
Original file line number Diff line number Diff line change
@@ -8,9 +8,19 @@
<img src="@/assets/icon_document.svg" style="width: 58%" alt="" />
</AppAvatar>
</slot>
<auto-tooltip :content="title" style="width: 65%">
{{ title }}
</auto-tooltip>
<div>
<auto-tooltip :content="title" style="width: 65%; height: 22px">
{{ title }}
</auto-tooltip>
<span class="lighter mr-8">
<auto-tooltip
:content="username"
style="display: inline-block; width: 100%; font-size: 12px; height: 20px"
>
创建人: {{ username }}
</auto-tooltip></span
>
</div>
</div>
</slot>
</div>
@@ -49,6 +59,7 @@ const props = withDefaults(
* 是否展示icon
*/
showIcon?: boolean
username?: string
}>(),
{ title: '标题', description: '', showIcon: true, border: true }
)
@@ -62,13 +73,12 @@ function cardEnter() {
}

function cardLeave() {
show.value = subHovered.value;
show.value = subHovered.value
}

function subHoveredEnter() {
subHovered.value = true
}

</script>
<style lang="scss" scoped>
.card-box {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code difference:

The code you provided contains some inconsistencies and stylistic issues which should be fixed to ensure the document is properly formatted according to best practices. However, please note that these suggestions may involve making changes to your current working environment since I don't have it available for testing.

Here's a general guideline of how you might clean up this HTML markup into proper CSS structure (CSS), ensuring good readability with semantic HTML tags, and following standard conventions like removing unnecessary elements or comments at the top level:

<div class="container">
    <div v-if="showIcon" class="card">
        <app-avatar @hover="subHoveredEnter">
            <!-- other avatar logic -->
        </app-avatar>
        <slot name="avatar"></slot>

        <!-- title & description -->
        <div class="text-center">
            <!-- ... -->
        </div>

        <div v-else class="card-body text-center" role="button" aria-label="Card body button">

            <!-- sub-hovered tooltip element -->
            <a class="cursor-pointer light hover:text-blueDark py-4 px-8 rounded-lg mb-2 transition-all duration-300 ease-in-out" tabindex="-1">@@</a>

            <!-- username tooltip -->

This will provide an improved layout while keeping your de#tact. Please let me know if there are other aspects such as specific formatting details that need addressing.

Remember to replace "@@" with the real placeholder content where necessary within <code>...:</code> tags for consistency in markdown syntax.

2 changes: 1 addition & 1 deletion ui/src/styles/variables.scss
Original file line number Diff line number Diff line change
@@ -34,7 +34,7 @@

/** card */
--card-width: 330px;
--card-min-height: 160px;
--card-min-height: 166px;
--card-min-width: 220px;

/** setting */
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

您好,很遗憾的是您的问题似乎没有提供具体的代码片段来看。如果您能提供具体的代码或描述更清晰的需求情况(例如:您想要比较的两个版本以及它们之间的改动点在哪里),我将尽力帮助您评估差异并提出可能的改善建议。另外请注意,在给出任何建议时,请确保是基于实际存在的差异进行分析和判断。

Loading
Loading