Пример #1
0
    def __init__(self, field_key_map: Optional[Dict[str, str]] = None) -> None:
        super().__init__(field_key_map=field_key_map)
        from drf_yasg.generators import OpenAPISchemaGenerator
        from drf_yasg.openapi import Info

        self.schema_generator = OpenAPISchemaGenerator(
            info=Info(title="", default_version=""))
Пример #2
0
def get_schema_view(info=None,
                    url=None,
                    patterns=None,
                    urlconf=None,
                    public=None,
                    validators=None,
                    generator_class=None,
                    authentication_classes=None,
                    permission_classes=None):
    if info is None:
        default_info = swagger_settings.DEFAULT_INFO or {}
        if isinstance(default_info, dict):
            default_info = default_info.copy()
            default_info.setdefault('title', 'api')
            default_info.setdefault('default_version', '1')
            info = Info(**default_info)
    return get_schema_view_base(info=info,
                                url=url,
                                patterns=patterns,
                                urlconf=urlconf,
                                public=True if public is None else public,
                                validators=validators,
                                generator_class=generator_class
                                or SchemaGenerator,
                                authentication_classes=authentication_classes
                                if authentication_classes is not None else (),
                                permission_classes=permission_classes
                                if permission_classes is not None else
                                (AllowAny, ))
Пример #3
0
def fetch_generated_schema(url: str, method: str,
                           status_code: Union[int, str]) -> dict:
    """
    Fetches a dynamically generated OpenAPI schema.

    :param url: API endpoint URL, str
    :param method: HTTP method, str
    :param status_code: HTTP response code
    :return: The section of the schema relevant for testing, dict
    """
    logger.debug('Fetching generated dynamic schema')
    from drf_yasg.openapi import Info
    from drf_yasg.generators import OpenAPISchemaGenerator

    # Fetch schema and convert to dict
    schema = OpenAPISchemaGenerator(
        info=Info(title='', default_version='')).get_schema()
    schema = loads(dumps(
        schema.as_odict()['paths']))  # Converts OrderedDict to dict

    try:
        schema = schema[url]
    except KeyError:
        raise OpenAPISchemaError(
            f'No path found for url `{url}`. Valid urls include {", ".join([key for key in schema.keys()])}'
        )

    try:
        schema = schema[method.lower()]['responses']
    except KeyError:
        raise OpenAPISchemaError(
            f'No schema found for method {method.upper()}. Available methods include '
            f'{", ".join([method.upper() for method in schema.keys() if method.upper() != "PARAMETERS"])}.'
        )

    try:
        schema = schema[f'{status_code}']['schema']
    except KeyError:
        raise OpenAPISchemaError(
            f'No schema found for response code {status_code}. Documented responses include '
            f'{", ".join([code for code in schema.keys()])}.')

    return schema
Пример #4
0
    def __init__(self,
                 route: str,
                 method: str,
                 status_code: Optional[int] = None,
                 **kwargs) -> None:
        """
        Loads OpenAPI schema when schema is dynamically generated by drf_yasg.

        :param route: a django-resolved endpoint path
        :param status_code: the relevant HTTP response status code to check in the OpenAPI schema
        :param method: the relevant HTTP method to check in the OpenAPI schema
        """
        validate_inputs(route=route, status_code=status_code, method=method)
        self.validation()

        from drf_yasg.openapi import Info
        from drf_yasg.generators import OpenAPISchemaGenerator

        self.schema_generator = OpenAPISchemaGenerator(
            info=Info(title='', default_version=''))

        self.route = self.get_drf_yasg_compatible_route(route)
        self.status_code = status_code
        self.method = method
Пример #5
0
from django.contrib import admin
from django.urls import path, include

from .settings import DEBUG

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('apps.accounts.urls'))
]

if DEBUG:
    from rest_framework.permissions import AllowAny
    from drf_yasg.openapi import Info
    from drf_yasg.views import get_schema_view

    info = Info(title='Tricks API',
                default_version='0.0.1',
                description='API description')
    schema_view = get_schema_view(
        info,
        permission_classes=(AllowAny, ),
        public=True,
    )
    swagger_view = schema_view.with_ui('swagger', cache_timeout=0)

    urlpatterns += [path('', swagger_view)]
Пример #6
0
from django.contrib import admin
from django.urls import path, include
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('first/', include('apps.first.urls')),
    path('other/', include('apps.other.urls')),
    path('proxy/', include('apps.proxy.urls')),
]

if settings.DEBUG:
    # Enable swagger
    from drf_yasg.views import get_schema_view
    from drf_yasg.openapi import Info
    from rest_framework.permissions import AllowAny

    info = Info(title='Main project', default_version='v1', description='...')
    schema_view = get_schema_view(info=info, permission_classes=(AllowAny, ))
    swagger_view = schema_view.with_ui('swagger')

    urlpatterns += [
        path('', swagger_view),
    ]
Пример #7
0
from drf_yasg.openapi import Contact
from drf_yasg.openapi import Info
from drf_yasg.openapi import License
from drf_yasg.views import get_schema_view
from rest_framework.permissions import AllowAny

schema_view = get_schema_view(
    Info(
        title="cruftbot",
        default_version="v1",
        description="Apply cruft tool continuously in pull requests",
        terms_of_service="https://github.com/proofit404/cruftbot/",
        contact=Contact(email="*****@*****.**"),
        license=License(name="BSD License"),
    ),
    public=True,
    permission_classes=(AllowAny, ),
)
Пример #8
0

schema_view = get_schema_view(
    Info(
        title="MERMAID Summary API",
        default_version='v1',
        description="""
This summary API provides public endpoints that provide access to MERMAID (https://datamermaid.org) data 
aggregated to different levels, for rapid consumption by third-party applications. For access to granular data 
restricted by authenticated user account, use the contact email below for more information about 
https://api.datamermaid.org.

All MERMAID projects elect a data sharing policy for each sample unit type (currently: belt fish transect, 
benthic LIT transect, benthic PIT transect, habitat complexity transect), currently one of: 
- "private": Summary information, including location and date, are available, but aggregated results and 
observations are not
- "public summary" (*default*): Like private, but with aggregated results
- "public": full observation-level data are available
So far this summary API provides only endpoints offering "private" and "public summary" data aggregated at 
the site level, but other levels and policies will be supported in the future. 

All api requests are throttled at the rate of 10000/second overall.
        """,
        terms_of_service="https://datamermaid.org/terms-of-service/",
        contact=Contact(email="*****@*****.**"),
        license=License(name="BSD License",
                        url="https://datamermaid.org/terms-of-service/"),
    ),
    # url='https://summary-api.datamermaid.org',
    public=True,
    generator_class=SummaryAPIGenerator)
Пример #9
0
from django.contrib import admin
from django.urls import path, include
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
]

if settings.DEBUG:
    from drf_yasg.openapi import Info
    from drf_yasg.views import get_schema_view
    from rest_framework.permissions import AllowAny

    schema_info = Info(title='Task board',
                       default_version='0.0.0',
                       description='...')
    schema_view = get_schema_view(info=schema_info,
                                  public=True,
                                  permission_classes=(AllowAny, ))

    swagger_view = schema_view.with_ui('swagger')

    urlpatterns += [path('', swagger_view)]
Пример #10
0
    Finding, JIRA_Instance, JIRA_Issue, DojoMeta, Note_Type, Notes, Product_Type, Product, Regulation, \
    Sonarqube_Issue, Sonarqube_Product, Sonarqube_Issue_Transition, \
    Stub_Finding, System_Settings, Test_Type, Test, Tool_Configuration, Tool_Product_Settings, \
    Tool_Type, Dojo_User, JIRA_Project, App_Analysis

from dojo.api_v2.serializers import \
    DevelopmentEnvironmentSerializer, EndpointStatusSerializer, EndpointSerializer, \
    EngagementSerializer, FindingTemplateSerializer, FindingSerializer, \
    JIRAInstanceSerializer, JIRAIssueSerializer, JIRAProjectSerializer, MetaSerializer, NoteTypeSerializer, \
    ProductSerializer, RegulationSerializer, \
    SonarqubeIssueSerializer, SonarqubeProductSerializer, SonarqubeIssueTransitionSerializer, \
    StubFindingSerializer, SystemSettingsSerializer, TestTypeSerializer, TestSerializer, ToolConfigurationSerializer, \
    ToolProductSettingsSerializer, ToolTypeSerializer, UserSerializer, NoteSerializer, ProductTypeSerializer, \
    AppAnalysisSerializer

SWAGGER_SCHEMA_GENERATOR = OpenAPISchemaGenerator(Info("defectdojo", "v2"))
BASE_API_URL = "/api/v2"


def testIsBroken(method):
    return tag("broken")(method)


def skipIfNotSubclass(baseclass):
    def decorate(f):
        def wrapper(self, *args, **kwargs):
            if not issubclass(self.viewset, baseclass):
                self.skipTest('This view is not %s' % baseclass)
            else:
                f(self, *args, **kwargs)
Пример #11
0
"""Schema generation with drf_yasg."""

from drf_yasg.inspectors import SwaggerAutoSchema
from drf_yasg.openapi import Info, License
from drf_yasg.views import get_schema_view
from drf_yasg.utils import no_body

schema_info = Info(
    title="Quicksell API",
    default_version='v1',
    license=License(name="Proprietary"),
)
schema_view = get_schema_view(schema_info, public=True)


class Read():
    """Serializer without write_only fields."""
    def get_fields(self):
        return {
            field_name: field
            for field_name, field in super().get_fields().items()
            if not field.write_only
        }


class Write():
    """Serializer without read_only fields."""
    def get_fields(self):
        return {
            field_name: field
            for field_name, field in super().get_fields().items()
Пример #12
0
from django.conf import settings
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf.urls.static import static
{%- if cookiecutter.use_drf_yasg == 'y' %}
from drf_yasg.openapi import Info, Contact
from drf_yasg.views import get_schema_view
from rest_framework.permissions import AllowAny
{%- endif %}

{%- if cookiecutter.use_drf_yasg == 'y' %}

schema_view = get_schema_view(
   Info(
      title='{{ cookiecutter.project_name }} API',
      default_version='v1',
      description='{{ cookiecutter.project_name }} project',
      contact=Contact(email='{{ cookiecutter.project_slug }}@example.com'),
   ),
   public=True,
   permission_classes=(AllowAny,),
)
{%- endif %}

urlpatterns = [
   path('admin/', admin.site.urls),
   {%- if cookiecutter.use_drf == 'y' %}
   path('api/v1/', include('config.urls_api_v1', namespace='api_v1')),
   {%- endif %}
   {%- if cookiecutter.use_drf_yasg == 'y' %}
   path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='redoc-ui'),
   path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
Пример #13
0
    path,
    re_path,
)
from drf_yasg.openapi import (
    Info,
    Contact,
    License,
)
from drf_yasg.views import get_schema_view
from rest_framework.permissions import AllowAny

schema_view = get_schema_view(
    Info(
        title="서울시 공영주차장 검색 API",
        default_version='v1',
        description=
        "서울열린데이터 광장의 '서울시 공영주차장 안내 정보'를 활용해서 주차 가능한 주차장을 찾을 수 있는 서비스 API",
        contact=Contact(email="*****@*****.**"),
        license=License(name="MIT License"),
    ),
    public=True,
    permission_classes=(AllowAny, ),
)

urlpatterns = [
    path('redoc/',
         schema_view.with_ui('redoc', cache_timeout=0),
         name='schema-redoc'),
    path('swagger/',
         schema_view.with_ui('swagger', cache_timeout=0),
         name='schema-swagger-ui'),
    re_path(r'^swagger(?P<format>\.json|\.yaml)$',