安装 drf-yasg
在你的 INSTALLED_APPS
中添加 drf_yasg
INSTALLED_APPS = [
# ...
'drf_yasg',
]
URL文件配置
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="Asset API",
default_version='v1',
description="APIs for my service",
contact=openapi.Contact(email="16340***@qq.com"),
license=openapi.License(name="Allow License"),
),
public=True,
)
urlpatterns = [
path('admin/', admin.site.urls),
path('vul/',include('VulScan.urls')),
path('asset/',include('assets.urls')),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]
配置View文件
# 登录接口
python
@swagger_auto_schema(
method="POST",
operation_summary='获取用户信息',
operation_description='获取token信息',
responses={
0: '返回用户信息',
1: '用户不存在'
},
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'username': openapi.Schema(type=openapi.TYPE_STRING),
'password': openapi.Schema(type=openapi.TYPE_STRING),
}
),
)
@api_view(['POST'])
def login(request):
# 显式设置 JSONParser
request.parser_classes = [JSONParser]
username = request.data.get('username')
password = request.data.get('password')
print(username,password)
user = authenticate(request, username=username, password=password)
if user is None:
return Response({'error': 'Invalid credentials','code':1,'msg':"登录失败,账号或密码错误"})
refresh = RefreshToken.for_user(user)
return Response({
'access_token': str(refresh.access_token),
'refresh_token': str(refresh),
'code':0,
'msg':'登录成功'
})