U
    Ç½„bÕR  ã                   @   sÆ   d dl Z d dlZd dlmZ ddlmZ ddlmZmZm	Z	m
Z
 eƒ Ze e¡Zdd„ Zddd	„ZG d
d„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZdS )é    N)Úserializersé   )Úopenapi)Úforce_real_strÚget_field_defaultÚget_object_classesÚis_list_viewc                 C   sJ   t | |ƒ}t |¡r(t |dd ƒr(|dfS ddlm} |t|| |d ƒtƒfS )NÚ__self__Tr   )Úgetattr_static)ÚgetattrÚinspectÚismethodr
   Ú
isinstanceÚstaticmethod)Zcls_or_instanceÚmethod_nameÚmethodr
   © r   ú</tmp/pip-unpacked-wheel-o6yr43pd/drf_yasg/inspectors/base.pyÚis_callable_method   s
    
r   c                 C   sp   t | |ƒrTzt| |ƒ\}}|r&|ƒ W S W n* tk
rR   tjdt| ƒjdd� Y nX |rlt | |ƒrlt| |ƒS |S )aþ  Call a view method which might throw an exception. If an exception is thrown, log an informative error message
    and return the value of fallback_attr, or default if not present. The method must be callable without any arguments
    except cls or self.

    :param view: view class or instance; if a class is passed, instance methods won't be called
    :type view: rest_framework.views.APIView or type[rest_framework.views.APIView]
    :param str method_name: name of a method on the view
    :param str fallback_attr: name of an attribute on the view to fall back on, if calling the method fails
    :param default: default value if all else fails
    :return: view method's return value, or value of view's fallback_attr, or default
    :rtype: any or None
    z…view's %s raised exception during schema generation; use `getattr(self, 'swagger_fake_view', False)` to detect and short-circuit thisT)Úexc_info)Úhasattrr   Ú	ExceptionÚloggerÚwarningÚtypeÚ__name__r   )Úviewr   Zfallback_attrÚdefaultZview_methodZis_callabaler   r   r   Úcall_view_method   s    
 þ
r   c                   @   s6   e Zd Zdd„ Zdd„ Zddd„Zdd	„ Zd
d„ ZdS )ÚBaseInspectorc                 C   s"   || _ || _|| _|| _|| _dS )aš  
        :param rest_framework.views.APIView view: the view associated with this endpoint
        :param str path: the path component of the operation URL
        :param str method: the http method of the operation
        :param openapi.ReferenceResolver components: referenceable components
        :param rest_framework.request.Request request: the request made against the schema view; can be None
        N)r   Úpathr   Ú
componentsÚrequest)Úselfr   r    r   r!   r"   r   r   r   Ú__init__7   s
    zBaseInspector.__init__c                 K   s   |S )aq  After an inspector handles an object (i.e. returns a value other than :data:`.NotHandled`), all inspectors
        that were probed get the chance to alter the result, in reverse order. The inspector that handled the object
        is the first to receive a ``process_result`` call with the object it just returned.

        This behaviour is similar to the Django request/response middleware processing.

        If this inspector has no post-processing to do, it should just ``return result`` (the default implementation).

        :param result: the return value of the winning inspector, or ``None`` if no inspector handled the object
        :param str method_name: name of the method that was called on the inspector
        :param obj: first argument passed to inspector method
        :param kwargs: additional arguments passed to inspector method
        :return:
        r   )r#   Úresultr   ÚobjÚkwargsr   r   r   Úprocess_resultE   s    zBaseInspector.process_resultNc           
      K   sÈ   |pi }g }|D ]~}t  |¡s&tdƒ‚t|tƒs8tdƒ‚|| j| j| j| j| j	f|Ž}| 
|¡ t||dƒ}|dkrvq||f|Ž}	|	tk	r q¤qt d|||¡ d}	t|ƒD ]}|j|	||f|Ž}	q¬|	S )af  Probe a list of inspectors with a given object. The first inspector in the list to return a value that
        is not :data:`.NotHandled` wins.

        :param list[type[BaseInspector]] inspectors: list of inspectors to probe
        :param str method_name: name of the target method on the inspector
        :param obj: first argument to inspector method
        :param dict initkwargs: extra kwargs for instantiating inspector class
        :param kwargs: additional arguments to inspector method
        :return: the return value of the winning inspector, or ``None`` if no inspector handled the object
        z(inspector must be a class, not an objectz&inspectors must subclass BaseInspectorNz@%s ignored because no inspector in %s handled it (operation: %s))r   ÚisclassÚAssertionErrorÚ
issubclassr   r   r    r   r!   r"   Úappendr   Ú
NotHandledr   r   Úreversedr(   )
r#   Ú
inspectorsr   r&   Z
initkwargsr'   Ztried_inspectorsZ	inspectorr   r%   r   r   r   Úprobe_inspectorsV   s,    
  ÿzBaseInspector.probe_inspectorsc                 C   s   t t| jddg ƒƒS )z¯Get the renderer classes of this view by calling `get_renderers`.

        :return: renderer classes
        :rtype: list[type[rest_framework.renderers.BaseRenderer]]
        Zget_renderersZrenderer_classes©r   r   r   ©r#   r   r   r   Úget_renderer_classes{   s    z"BaseInspector.get_renderer_classesc                 C   s   t t| jddg ƒƒS )z¥Get the parser classes of this view by calling `get_parsers`.

        :return: parser classes
        :rtype: list[type[rest_framework.parsers.BaseParser]]
        Zget_parsersZparser_classesr1   r2   r   r   r   Úget_parser_classesƒ   s    z BaseInspector.get_parser_classes)N)r   Ú
__module__Ú__qualname__r$   r(   r0   r3   r4   r   r   r   r   r   6   s
   
%r   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )ÚPaginatorInspectorz�Base inspector for paginators.

    Responisble for determining extra query parameters and response structure added by given paginators.
    c                 C   s   t S )a  Get the pagination parameters for a single paginator **instance**.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `paginator`.

        :param BasePagination paginator: the paginator
        :rtype: list[openapi.Parameter]
        ©r-   )r#   Ú	paginatorr   r   r   Úget_paginator_parameters’   s    z+PaginatorInspector.get_paginator_parametersc                 C   s   t S )ad  Add appropriate paging fields to a response :class:`.Schema`.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `paginator`.

        :param BasePagination paginator: the paginator
        :param openapi.Schema response_schema: the response schema that must be paged.
        :rtype: openapi.Schema
        r8   )r#   r9   Úresponse_schemar   r   r   Úget_paginated_responseœ   s    	z)PaginatorInspector.get_paginated_responseN)r   r5   r6   Ú__doc__r:   r<   r   r   r   r   r7   Œ   s   
r7   c                   @   s   e Zd ZdZdd„ ZdS )ÚFilterInspectorz€Base inspector for filter backends.

    Responsible for determining extra query parameters added by given filter backends.
    c                 C   s   t S )a.  Get the filter parameters for a single filter backend **instance**.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `filter_backend`.

        :param BaseFilterBackend filter_backend: the filter backend
        :rtype: list[openapi.Parameter]
        r8   )r#   Úfilter_backendr   r   r   Úget_filter_parameters®   s    z%FilterInspector.get_filter_parametersN)r   r5   r6   r=   r@   r   r   r   r   r>   ¨   s   r>   c                       s@   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Z‡  Z	S )ÚFieldInspectorz6Base inspector for serializers and serializer fields. c                    s"   t t| ƒ |||||¡ || _d S )N)ÚsuperrA   r$   Úfield_inspectors)r#   r   r    r   r!   r"   rC   ©Ú	__class__r   r   r$   ¼   s    zFieldInspector.__init__c                 C   s>   t |ddƒ}t |di ƒ}|r:| ¡ D ]\}}t|||ƒ q$dS )aU  Set fields from the ``swagger_schem_fields`` attribute on the Meta class. This method is called
        only for serializers or fields that are converted into ``openapi.Schema`` objects.

        :param serializer_or_field: serializer or field instance
        :param openapi.Schema schema: the schema object to be modified in-place
        ZMetaNÚswagger_schema_fields)r   ÚitemsÚsetattr)r#   Zserializer_or_fieldZschemaÚmetarF   ÚattrÚvalr   r   r   Úadd_manual_fieldsÀ   s
    z FieldInspector.add_manual_fieldsc                 K   s   t S )a  Convert a drf Serializer or Field instance into a Swagger object.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `field`.

        :param rest_framework.serializers.Field field: the source field
        :param type[openapi.SwaggerDict] swagger_object_type: should be one of Schema, Parameter, Items
        :param bool use_references: if False, forces all objects to be declared inline
           instead of by referencing other components
        :param kwargs: extra attributes for constructing the object;
           if swagger_object_type is Parameter, ``name`` and ``in_`` should be provided
        :return: the swagger object
        :rtype: openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef
        r8   ©r#   ÚfieldÚswagger_object_typeÚuse_referencesr'   r   r   r   Úfield_to_swagger_objectÍ   s    z&FieldInspector.field_to_swagger_objectc                 K   s&   | j | jd|d| jif||dœ|—ŽS )zþHelper method for recursively probing `field_inspectors` to handle a given field.

        All arguments are the same as :meth:`.field_to_swagger_object`.

        :rtype: openapi.Parameter or openapi.Items or openapi.Schema or openapi.SchemaRef
        rQ   rC   )rO   rP   ©r0   rC   rM   r   r   r   Úprobe_field_inspectorsÝ   s       ÿ þþz%FieldInspector.probe_field_inspectorsc                    s¶   ˆt jt jt jfkst‚tˆt jƒr,tdƒ‚ˆjr<tˆjƒnd‰ˆt jkrNˆnd‰t	ˆddƒ}|rjt|ƒnd‰ ˆt jkr|ˆ nd‰ d‡ ‡‡‡‡‡fdd„	}ˆt jkr¨t jnt j}||fS )a[  Helper method to extract generic information from a field and return a partial constructor for the
        appropriate openapi object.

        All arguments are the same as :meth:`.field_to_swagger_object`.

        The return value is a tuple consisting of:

        * a function for constructing objects of `swagger_object_type`; its prototype is: ::

            def SwaggerType(existing_object=None, **instance_kwargs):

          This function creates an instance of `swagger_object_type`, passing the following attributes to its init,
          in order of precedence:

            - arguments specified by the ``kwargs`` parameter of :meth:`._get_partial_types`
            - ``instance_kwargs`` passed to the constructor function
            - ``title``, ``description``, ``required``, ``x-nullable`` and ``default`` inferred from the field,
              where appropriate

          If ``existing_object`` is not ``None``, it is updated instead of creating a new object.

        * a type that should be used for child objects if `field` is of an array type. This can currently have two
          values:

            - :class:`.Schema` if `swagger_object_type` is :class:`.Schema`
            - :class:`.Items` if `swagger_object_type` is  :class:`.Parameter` or :class:`.Items`

        :rtype: (function,type[openapi.Schema] or type[openapi.Items])
        z,passed field is already a SwaggerDict objectNÚ	help_textTc                    sü   d|krˆt jkrˆj|d< d|krLˆt jkrLtˆƒ}|d tjfkrL||d< |rn| dd ¡t jkrn| 	dˆ¡ ˆ d k	r‚| 	dˆ ¡ ˆj
r�d|d< | ˆ¡ | d k	rØt| ˆƒs°t‚t| ¡ ƒD ]\}}t| ||ƒ q¼| }n
ˆf |Ž}ˆt jkrøˆ ˆ|¡ |S )NÚrequiredr   r   ÚtitleÚdescriptionTZ
x_nullable)r   Ú	ParameterrU   ÚItemsr   r   ÚemptyÚgetÚ
TYPE_ARRAYÚ
setdefaultZ
allow_nullÚupdater   r*   ÚsortedrG   rH   ÚSchemarL   )Zexisting_objectZuse_field_titleZinstance_kwargsr   ÚkeyrK   r%   ©rW   rN   r'   r#   rO   rV   r   r   ÚSwaggerType  s,    



z6FieldInspector._get_partial_types.<locals>.SwaggerType)NT)
r   r`   rX   rY   r*   r   ZSwaggerDictÚlabelr   r   )r#   rN   rO   rP   r'   rT   rc   Zchild_swagger_typer   rb   r   Ú_get_partial_typesé   s    !z!FieldInspector._get_partial_types)
r   r5   r6   r=   r$   rL   rQ   rS   re   Ú__classcell__r   r   rD   r   rA   ¹   s   rA   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚSerializerInspectorc                 C   s   t S )a-  Convert a DRF Serializer instance to an :class:`.openapi.Schema`.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`.

        :param serializers.BaseSerializer serializer: the ``Serializer`` instance
        :rtype: openapi.Schema
        r8   ©r#   Ú
serializerr   r   r   Ú
get_schema5  s    zSerializerInspector.get_schemac                 C   s   t S )a�  Convert a DRF serializer into a list of :class:`.Parameter`\ s.

        Should return :data:`.NotHandled` if this inspector does not know how to handle the given `serializer`.

        :param serializers.BaseSerializer serializer: the ``Serializer`` instance
        :param str in_: the location of the parameters, one of the `openapi.IN_*` constants
        :rtype: list[openapi.Parameter]
        r8   ©r#   ri   Úin_r   r   r   Úget_request_parameters?  s    	z*SerializerInspector.get_request_parametersN)r   r5   r6   rj   rm   r   r   r   r   rg   4  s   
rg   c                       sŒ   e Zd ZdZdZdZg Zg Zg Z‡ fdd„Z	dd„ Z
dd	„ Zd
d„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Z‡  ZS )ÚViewInspector)ÚPUTÚPATCHÚPOSTÚDELETE)ro   rp   rq   )ÚGETc                    s@   t t| ƒ |||||¡ || _|  d¡ |  d¡ |  d¡ dS )zì
        Inspector class responsible for providing :class:`.Operation` definitions given a view, path and method.

        :param dict overrides: manual overrides as passed to :func:`@swagger_auto_schema <.swagger_auto_schema>`
        rC   Úfilter_inspectorsÚpaginator_inspectorsN)rB   rn   r$   Ú	overridesÚ_prepend_inspector_overrides)r#   r   r    r   r!   r"   rv   rD   r   r   r$   Y  s
    

zViewInspector.__init__c                    s>   | j  |d ¡‰ ˆ r:‡ fdd„t| |ƒD ƒ}t| |ˆ | ƒ d S )Nc                    s   g | ]}|ˆ kr|‘qS r   r   )Ú.0Zinsp©Zextra_inspectorsr   r   Ú
<listcomp>h  s      z>ViewInspector._prepend_inspector_overrides.<locals>.<listcomp>)rv   r[   r   rH   )r#   r/   Zdefault_inspectorsr   ry   r   rw   e  s    z*ViewInspector._prepend_inspector_overridesc                 C   s   t dƒ‚dS )aw  Get an :class:`.Operation` for the given API endpoint (path, method).
        This includes query, body parameters and response schemas.

        :param tuple[str] operation_keys: an array of keys describing the hierarchical layout of this view in the API;
          e.g. ``('snippets', 'list')``, ``('snippets', 'retrieve')``, etc.
        :rtype: openapi.Operation
        z-ViewInspector must implement get_operation()!N)ÚNotImplementedError)r#   Zoperation_keysr   r   r   Úget_operationk  s    zViewInspector.get_operationc                 C   s   t | j| j| jƒS )aÀ  Determine whether this view is a list or a detail view. The difference between the two is that
        detail views depend on a pk/id path parameter. Note that a non-detail view does not necessarily imply a list
        reponse (:meth:`.has_list_response`), nor are list responses limited to non-detail views.

        For example, one might have a `/topic/<pk>/posts` endpoint which is a detail view that has a list response.

        :rtype: bool)r   r    r   r   r2   r   r   r   r   u  s    zViewInspector.is_list_viewc                 C   s   |   ¡ o| j ¡ | jkS )zçDetermine whether this view returns multiple objects. By default this is any non-detail view
        (see :meth:`.is_list_view`) whose request method is one of :attr:`.implicit_list_response_methods`.

        :rtype: bool
        )r   r   ÚupperÚimplicit_list_response_methodsr2   r   r   r   Úhas_list_response  s    zViewInspector.has_list_responsec                 C   s   t | jddƒo|  ¡ S )zoDetermine whether filter backend parameters should be included for this request.

        :rtype: bool
        Úfilter_backendsN©r   r   r   r2   r   r   r   Úshould_filter‡  s    zViewInspector.should_filterc                 C   s@   |   ¡ sg S g }t| jdƒD ]}||  | jd|ƒ ¡p6g 7 }q|S )zqReturn the parameters added to the view by its filter backends.

        :rtype: list[openapi.Parameter]
        r€   r@   )r‚   r   r   r0   rt   )r#   Úfieldsr?   r   r   r   r@   Ž  s    z#ViewInspector.get_filter_parametersc                 C   s   t | jddƒo|  ¡ S )zŠDetermine whether paging parameters and structure should be added to this operation's request and response.

        :rtype: bool
        r9   Nr�   r2   r   r   r   Úshould_pageœ  s    zViewInspector.should_pagec                 C   s(   |   ¡ sg S |  | jdt| jdƒ¡p&g S )zkReturn the parameters added to the view by its paginator.

        :rtype: list[openapi.Parameter]
        r:   r9   )r„   r0   ru   r   r   r2   r   r   r   Úget_pagination_parameters£  s    

ÿÿz'ViewInspector.get_pagination_parametersc                 C   s   |   | jd|d| ji¡S )a#  Convert a serializer to an OpenAPI :class:`.Schema`.

        :param serializers.BaseSerializer serializer: the ``Serializer`` instance
        :returns: the converted :class:`.Schema`, or ``None`` in case of an unknown serializer
        :rtype: openapi.Schema or openapi.SchemaRef
        rj   rC   rR   rh   r   r   r   Úserializer_to_schema®  s       ÿz"ViewInspector.serializer_to_schemac                 C   s    | j | jd|d| ji|d�pg S )a(  Convert a serializer to a possibly empty list of :class:`.Parameter`\ s.

        :param serializers.BaseSerializer serializer: the ``Serializer`` instance
        :param str in_: the location of the parameters, one of the `openapi.IN_*` constants
        :rtype: list[openapi.Parameter]
        rm   rC   )rl   rR   rk   r   r   r   Úserializer_to_parameters¹  s       þýz&ViewInspector.serializer_to_parametersc                 C   s   | j | jdt| jdƒ|d�S )a+  Add appropriate paging fields to a response :class:`.Schema`.

        :param openapi.Schema response_schema: the response schema that must be paged.
        :returns: the paginated response class:`.Schema`, or ``None`` in case of an unknown pagination scheme
        :rtype: openapi.Schema
        r<   r9   )r;   )r0   ru   r   r   )r#   r;   r   r   r   r<   Å  s    

 ÿz$ViewInspector.get_paginated_response)r   r5   r6   Zbody_methodsZimplicit_body_methodsr~   rC   rt   ru   r$   rw   r|   r   r   r‚   r@   r„   r…   r†   r‡   r<   rf   r   r   rD   r   rn   K  s$   

rn   )NN)r   ÚloggingZrest_frameworkr   Ú r   Úutilsr   r   r   r   Úobjectr-   Ú	getLoggerr   r   r   r   r   r7   r>   rA   rg   rn   r   r   r   r   Ú<module>   s   


V{