Skip to content
Merged
Show file tree
Hide file tree
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
21 changes: 17 additions & 4 deletions apps/common/init/init_doc.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,34 @@

def init_app_doc(system_urlpatterns):
system_urlpatterns += [
path('doc/schema/', SpectacularAPIView.as_view(), name='schema'), # schema的配置文件的路由,下面两个ui也是根据这个配置文件来生成的
path('doc/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), # swagger-ui的路由
path(f'{CONFIG.get_admin_path()[1:]}/api-doc/schema/', SpectacularAPIView.as_view(), name='schema'),
# schema的配置文件的路由,下面两个ui也是根据这个配置文件来生成的
path(f'{CONFIG.get_admin_path()[1:]}/api-doc/', SpectacularSwaggerView.as_view(url_name='schema'),
name='swagger-ui'), # swagger-ui的路由
]


class ChatSpectacularSwaggerView(SpectacularSwaggerView):
@staticmethod
def _swagger_ui_resource(filename):
return f'{CONFIG.get_chat_path()}/api-doc/swagger-ui-dist/{filename}'

@staticmethod
def _swagger_ui_favicon():
return f'{CONFIG.get_chat_path()}/api-doc/swagger-ui-dist/favicon-32x32.png'


def init_chat_doc(system_urlpatterns, chat_urlpatterns):
system_urlpatterns += [
path('doc_chat/schema/',
path(f'{CONFIG.get_chat_path()[1:]}/api-doc/schema/',
SpectacularAPIView.as_view(patterns=[
URLPattern(pattern=f'{chat_api_prefix}{str(url.pattern)}', callback=url.callback,
default_args=url.default_args,
name=url.name) for url in chat_urlpatterns if
['chat', 'open', 'profile'].__contains__(url.name)]),
name='chat_schema'), # schema的配置文件的路由,下面两个ui也是根据这个配置文件来生成的
path('doc_chat/', SpectacularSwaggerView.as_view(url_name='chat_schema'), name='swagger-ui'), # swagger-ui的路由
path(f'{CONFIG.get_chat_path()[1:]}/api-doc/', ChatSpectacularSwaggerView.as_view(url_name='chat_schema'),
name='swagger-ui'), # swagger-ui的路由
]


Copy link
Contributor Author

Choose a reason for hiding this comment

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

The code looks generally correct, but there are a few minor issues and optimizations that can be made:

  1. Use path instead of string concatenation: It's more pythonic to use the path function from Django URLs compared to string concatenation. This makes the code cleaner and easier to read.

  2. Consistent spacing around operators and brackets: Ensure consistent formatting for readability, especially outside parentheses and between operators like = and ,.

  3. Remove unnecessary comments at the end of lines: Python doesn't require trailing comments on inline strings. Remove these for better readability.

Here is the revised version of the code:

def init_app_doc(system_urlpatterns):
    system_urlpatterns += [
        path(
            f'{CONFIG.get_admin_path()[1:]}/api-doc/schema/',
            SpectacularAPIView.as_view(),
            name='schema'
        ),
        # schema的配置文件的路由,下面两个ui也是根据这个配置文件来生成的
        path(  # Swagger UI的路由
            f'{CONFIG.get_admin_path()[1:]}/api-doc/',
            SpectacularSwaggerView.as_view(url_name='schema'),
            name='swagger-ui'
        )
    ]

class ChatSpectacularSwaggerView(SpectacularSwaggerView):
    @staticmethod
    def _swagger_ui_resource(filename):
        return f'{CONFIG.get_chat_path()}/api-doc/swagger-ui-dist/{filename}'

    @staticmethod
    def _swagger_ui_favicon():
        return f'{CONFIG.get_chat_path()}/api-doc.swagger-ui-dist/favicon-32x32.png'


def init_chat_doc(system_urlpatterns, chat_urlpatterns):
    system_urlpatterns.append(   # Append app doc URL patterns to the main system URL list
        path(
            f'{CONFIG.get_chat_path()[1:]}/api-doc/schema/',
             SpectacularAPIView.as_view(patterns=[  # Create a new route with specific pattern
                 # Iterate over each URL pattern in chat_urlpatterns
                 URLPattern(pattern=f'{chat_api_prefix}{str(url.pattern)}', callback=url.callback,
                            default_args=url.default_args, name=url.name)
                 for url in chat_urlpatterns if 'chat' in url.name],
                         name='chat_schema')  # Name for this route

         )  # Swagger UI route for chat API documentation
    )

These changes will make the code slightly cleaner and more maintainable.

Expand Down
6 changes: 3 additions & 3 deletions apps/maxkb/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,9 @@
'VERSION': 'v2',
'SERVE_INCLUDE_SCHEMA': False,
# OTHER SETTINGS
'SWAGGER_UI_DIST': '/doc/swagger-ui-dist', # shorthand to use the sidecar instead
'SWAGGER_UI_FAVICON_HREF': '/doc/swagger-ui-dist/favicon-32x32.png',
'REDOC_DIST': '/doc/redoc',
'SWAGGER_UI_DIST': f'{CONFIG.get_admin_path()}/api-doc/swagger-ui-dist', # shorthand to use the sidecar instead
'SWAGGER_UI_FAVICON_HREF': f'{CONFIG.get_admin_path()}/api-doc/swagger-ui-dist/favicon-32x32.png',
'REDOC_DIST': f'{CONFIG.get_admin_path()}/api-doc/redoc',
'SECURITY_DEFINITIONS': {
'Bearer': {
'type': 'apiKey',
Expand Down
7 changes: 6 additions & 1 deletion apps/maxkb/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,14 @@

def pro():
urlpatterns.append(
re_path(r'^doc/(?P<path>.*)$', static.serve,
re_path(rf'^{CONFIG.get_admin_path()[1:]}/api-doc/(?P<path>.*)$', static.serve,
{'document_root': os.path.join(settings.STATIC_ROOT, "drf_spectacular_sidecar")}, name='doc'),
)

urlpatterns.append(
re_path(rf'^{CONFIG.get_chat_path()[1:]}/api-doc/(?P<path>.*)$', static.serve,
{'document_root': os.path.join(settings.STATIC_ROOT, "drf_spectacular_sidecar")}, name='doc_chat'),
)
# 暴露ui静态资源
urlpatterns.append(
re_path(rf"^{CONFIG.get_admin_path()[1:]}/(?P<path>.*)$", static.serve,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code is mostly syntactically and semantically correct. However, there are a few improvements that can be made:

  1. Duplicated API Documentation URLs: The duplicate api-doc URL patterns will clash with each other when both paths point to different endpoints within the application. It would be better to rename these to avoid conflicts.

  2. Use of Regular Expressions: In Python 3.x, using single quotes (') instead of double quotes (") for string literals does not affect functionality but it's generally recommended for consistency.

Here's the optimized version of the code:

@@ -52,9 +52,14 @@
 
 def pro():
     urlpatterns.append(
-        re_path(r'^doc/(?P<path>.*)$', static.serve,
+        re_path(rf'^{CONFIG.get_admin_path()[1:]}/openapi/(?P<path>.*)$', static.serve,
                 {'document_root': os.path.join(settings.STATIC_ROOT, "drf_spectacular_sidecar"), 'name': 'openapi'},
             ),
         )
+
+    urlpatterns.append(
+        re_path(rf'^{CONFIG.get_chat_path()[1:]}/openapi/(?P<path>.*)$', static.serve,
+                {'document_root': os.path.join(settings.STATIC_ROOT, "drf_spectacular_sidecar"), 'name': 'openapi_chat'},
+            ),
+    )
     # 暴露ui静态资源
     urlpatterns.append(
         re_path(rf"^/{CONFIG.get_admin_path()[1:]}/(?P<path>.*)$", static.serve,

Key Changes:

  • Changed 'doc/' to 'openapi/'.
  • Added an `{'name': '...'} dictionary entry to give a unique name to the openAPI endpoint.
  • Renamed the second set of API documentation URLs accordingly (.chat/).

These changes make the code more maintainable and prevent potential conflicts with different types or categories of API documentation. Additionally, providing meaningful names can be helpful for easier management and documentation.

Expand Down
8 changes: 3 additions & 5 deletions ui/src/layout/layout-header/avatar/APIKeyDialog.vue
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
<span class="mr-4">
<el-tooltip effect="dark" :content="$t('common.setting')" placement="top">
<el-button type="primary" text @click.stop="settingApiKey(row)">
<AppIcon iconName="app-setting"></AppIcon>
<AppIcon iconName="app-setting"></AppIcon>
</el-button>
</el-tooltip>
</span>
Expand Down Expand Up @@ -87,7 +87,7 @@ const props = defineProps({
})
const emit = defineEmits(['addData'])

const apiUrl = window.location.origin + '/doc/'
const apiUrl = window.location.origin + +`${window.MaxKB.prefix}/api-doc/`
const SettingAPIKeyDialogRef = ref()
const dialogVisible = ref<boolean>(false)
const loading = ref(false)
Expand Down Expand Up @@ -126,9 +126,7 @@ function changeState(bool: boolean, row: any) {
const obj = {
is_active: bool,
}
const str = bool
? t('common.enabled')
: t('common.disabled')
const str = bool ? t('common.enabled') : t('common.disabled')
systemKeyApi.putAPIKey(row.id, obj, loading).then((res) => {
MsgSuccess(str)
getApiKeyList()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

The provided code has a small issue and can be improved slightly:

  1. Suggested Changes:

    The error seems to be due to an incorrect way of concatenating strings in JavaScript. Instead of window.location.origin + +${window.MaxKB.prefix}/api-doc/, it should be fixed using a template literal.

  2. Corrected Code Snippet:

Here's the corrected version of the relevant part of your code:

const apiUrl = window.location.origin + `${(window?.MaxKB ?? {}).prefix || ''}/api-doc/`;

Explanation:

  • Using (window?.MaxKB ?? '') ensures that if window?.MaxKB does not exist (i.e., this might happen on some platforms), it defaults to an empty string, preventing errors from the concatenation.
  • Added {} around MaxKB to correctly access its properties when available.

This change will prevent any issues related to undefined values or improper string concatenation.

Note: Ensure that maxKB is defined with a prefix before making calls like these to avoid further errors.

Expand Down
2 changes: 1 addition & 1 deletion ui/src/views/application-overview/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ const permissionPrecise = computed(() => {
return permissionMap['application'][apiType.value]
})

const apiUrl = window.location.origin + '/doc_chat/'
const apiUrl = window.location.origin + `${window.MaxKB.chatPrefix}/api-doc/`

const baseUrl = window.location.origin + `${window.MaxKB.chatPrefix}/api/`

Expand Down
Loading