52 lines
1.5 KiB
Markdown
52 lines
1.5 KiB
Markdown
|
|
|
|
Для начала, установим необходимые библиотеки:
|
|
|
|
```
|
|
pip install drf-yasg pyyaml
|
|
```
|
|
|
|
После этого создайте файл `swagger_generator.py` и добавьте следующий код:
|
|
|
|
|
|
```
|
|
from rest_framework.schemas import SchemaGenerator
|
|
from rest_framework.permissions import AllowAny
|
|
from rest_framework.views import APIView
|
|
from drf_yasg import openapi
|
|
from drf_yasg.views import get_schema_view
|
|
import yaml
|
|
|
|
# Создаем схему Swagger для API
|
|
schema_view = get_schema_view(
|
|
openapi.Info(
|
|
title="Your API",
|
|
default_version='v1',
|
|
description="API Description",
|
|
terms_of_service="https://www.google.com/policies/terms/",
|
|
contact=openapi.Contact(email="contact@example.com"),
|
|
license=openapi.License(name="BSD License"),
|
|
),
|
|
public=True,
|
|
permission_classes=(AllowAny,),
|
|
)
|
|
# Создаем класс для генерации YAML-файла
|
|
class SwaggerYAMLGenerator(APIView):
|
|
def get(self, request):
|
|
generator = SchemaGenerator()
|
|
schema = generator.get_schema(request=request)
|
|
yaml_data = yaml.dump(schema.to_dict(),
|
|
default_flow_style=False)
|
|
return Response(yaml_data, content_type='application/yaml')
|
|
```
|
|
|
|
Затем добавьте URL для обработки запросов Swagger в файле `urls.py` вашего Django-приложения:
|
|
|
|
```
|
|
from django.urls import path
|
|
from .swagger_generator import SwaggerYAMLGenerator
|
|
|
|
urlpatterns = [
|
|
path('swagger.yaml', SwaggerYAMLGenerator.as_view()),
|
|
]
|
|
``` |