OpenAPI Django
Библиотека для автоматической генерации OpenAPI файла для Django проектов.
Использование
Устанавливаем библиотеку
pip install openapi-django
Добавляем в проект
В файле {ProjectPath}/{DjangoFolder}/settings.py находим секцию INSTALLED_APPS и добавляем имя библиотеки.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'openapi_django'
]
Настройка
Настройка производится добавлением словаря OPENAPI_DJANGO в файл {ProjectPath}/{DjangoFolder}/settings.py
Используемые ключи:
servers- Список серверов, которые нужно добавить на страницу OpenAPI (Учитывайте что если вsettings.pyуказаноDEBUG = Trueто на страницу автоматически будет добавлен сервер изrequest.META["HTTP_HOST"]запроса)version- Версия вашего приложенияtitle- Имя приложения
Пример:
OPENAPI_DJANGO = {
"servers": ["https://test.test"],
"version": "0.0.1",
"title": "Test project"
}
Добавление url для отображения страницы OpenAPI
В файле {ProjectPath}/{DjangoFolder}/urls.py добавить:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('openapi/', include('openapi_django.urls')),
]
Библиотека добавляет 2 урла:
- "/" - отображает страницу OpenAPI
- "/file" - json файл данных OpenAPI
Использование
Простое добавление информации о запросе без указание возвращаемых и используемых данных
from django.views import View
from django.http import HttpResponse
from openapi_django.openapi_utils.decorators import openapi
class MyView(View):
@openapi()
def get(self, request):
html = "<html>Hello world</html>"
return HttpResponse(html)
С указанием используемых данных
Поддерживаются переменные классов "pydantic" и "djantic")
import json
from typing import Optional, List
from django.views import View
from django.http import JsonResponse
from djantic import ModelSchema
from pydantic.main import BaseModel
from pydantic.fields import Field
from openapi_django.openapi_utils.decorators import openapi
from test_app.models import MyModel
class MyModelSchema(ModelSchema):
class Config:
model = MyModel
class GetReturnClassSchema(BaseModel):
data: List[MyModelSchema] = Field(description="Список объектов")
class ObjectReturnClassSchema(BaseModel):
data: MyModelSchema = Field(description="Данные нового объекта")
class ParametersSchema(BaseModel):
name: Optional[str] = Field(description="Имя")
color: Optional[str] = Field(description="Любимый цвет")
class PostBodySchema(BaseModel):
name: str = Field(description="Имя")
color: Optional[str] = Field(description="Любимый цвет")
class PathParameterSchema(BaseModel):
param_path_id: int = Field(description="ID объекта")
class PostFileSchema(BaseModel):
file: bytes
class MyModelsView(View):
@openapi(
description="Получение всех обьектов",
return_class=GetReturnClassSchema,
parameters=ParametersSchema)
def get(self, request):
items = MyModel.objects.filter(**request.GET.dict())
return JsonResponse(data={"data": [MyModelSchema.from_orm(item).dict() for item in items]})
@openapi(
description="Добавление обьекта",
return_class=ObjectReturnClassSchema,
body=PostBodySchema
)
def post(self, request):
item = MyModel(**json.loads(request.body))
item.save()
return JsonResponse(data={"data": MyModelSchema.from_orm(item).dict()})
class MyModelPathView(View):
@openapi(
description="Получение данных объекта",
return_class=ObjectReturnClassSchema,
path_parameters=PathParameterSchema
)
def get(self, request, param_path_id):
item = MyModel.objects.get(pk=param_path_id)
return JsonResponse(data={"data": MyModelSchema.from_orm(item).dict()})
class MyModelFileView(View):
@openapi(
description="Отправка файла",
answer_content="multipart/form-data",
body=PostFileSchema
)
def post(self, request):
content = request.FILES.get("file").read().decode('utf8')
return JsonResponse(data={"msg": 'OK'})
Metadata
Release files for openapi-django 1.4.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| openapi_django-1.4.1.tar.gz | 34.8 kB | Without provenance | Details for openapi_django-1.4.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| openapi_django-1.4.1-py3-none-any.whl | Python 3 | none | any | Details for openapi_django-1.4.1-py3-none-any.whl |
Total release size: 76.8 kB
Release files / openapi_django-1.4.1.tar.gz
| Download URL | openapi_django-1.4.1.tar.gz |
|---|---|
| Size | 34.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
02d413f8c3998cea1f5a54176da2af3112c55b953e916e7800833aa6f618c89a
|
|
BLAKE2b-256 checksum How to use checksums |
852116ea620323099d0aa6c684e8ca736df75f6ecc9d34687901f929ddb3a3f2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.1
|
Release files / openapi_django-1.4.1-py3-none-any.whl
| Download URL | openapi_django-1.4.1-py3-none-any.whl |
|---|---|
| Size | 41.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8be390904566572d9988930c62ff648efdb9c145148f46f5ca54e20b6ac55133
|
|
BLAKE2b-256 checksum How to use checksums |
e4f75a8d8925217b73d89e35eb4178aaef3346a083ad146f7c2b426d52961f6c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.11.1
|
Security for openapi-django 1.4.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.