U
    Ç½„b¬]  ã                   @   s¨  d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZmZ d dlmZmZmZmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZ d dlmZ ddl m!Z! e "e#¡Z$G dd„ de%ƒZ&G dd„ de%ƒZ'dde'ddddddddddddd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$„ Z0d:d%d&„Z1d'd(„ Z2d)d*„ Z3d+d,„ Z4d-d.„ Z5d;d2d3„Z6d4d5„ Z7d6d7„ Z8d8d9„ Z9dS )<é    N)ÚOrderedDict)ÚDecimal)Úmodels)Ú	force_str)ÚserializersÚstatus)ÚDestroyModelMixinÚListModelMixinÚRetrieveModelMixinÚUpdateModelMixin)ÚFileUploadParser©Úis_form_media_type)Úapi_settings)ÚencodersÚjson)ÚAPIViewé   )Úswagger_settingsc                   @   s   e Zd ZdZdS )Úno_bodyzcUsed as a sentinel value to forcibly remove the body of a request via :func:`.swagger_auto_schema`.N©Ú__name__Ú
__module__Ú__qualname__Ú__doc__© r   r   ú2/tmp/pip-unpacked-wheel-o6yr43pd/drf_yasg/utils.pyr      s   r   c                   @   s   e Zd ZdZdS )ÚunsetzmUsed as a sentinel value for function parameters not set by the caller where ``None`` would be a valid value.Nr   r   r   r   r   r      s   r   c                    s0   ‡ ‡‡‡‡‡‡‡‡‡	‡
‡‡‡‡‡‡fdd„}|S )a¼  Decorate a view method to customize the :class:`.Operation` object generated from it.

    `method` and `methods` are mutually exclusive and must only be present when decorating a view method that accepts
    more than one HTTP request method.

    The `auto_schema` and `operation_description` arguments take precedence over view- or method-level values.

    :param str method: for multi-method views, the http method the options should apply to
    :param list[str] methods: for multi-method views, the http methods the options should apply to
    :param drf_yasg.inspectors.SwaggerAutoSchema auto_schema: custom class to use for generating the Operation object;
        this overrides both the class-level ``swagger_schema`` attribute and the ``DEFAULT_AUTO_SCHEMA_CLASS``
        setting, and can be set to ``None`` to prevent this operation from being generated
    :param request_body: custom request body which will be used as the ``schema`` property of a
        :class:`.Parameter` with ``in: 'body'``.

        A Schema or SchemaRef is not valid if this request consumes form-data, because ``form`` and ``body`` parameters
        are mutually exclusive in an :class:`.Operation`. If you need to set custom ``form`` parameters, you can use
        the `manual_parameters` argument.

        If a ``Serializer`` class or instance is given, it will be automatically converted into a :class:`.Schema`
        used as a ``body`` :class:`.Parameter`, or into a list of ``form`` :class:`.Parameter`\ s, as appropriate.
    :type request_body: drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef  or rest_framework.serializers.Serializer
        or type[no_body]

    :param rest_framework.serializers.Serializer query_serializer: if you use a ``Serializer`` to parse query
        parameters, you can pass it here and have :class:`.Parameter` objects be generated automatically from it.

        If any ``Field`` on the serializer cannot be represented as a ``query`` :class:`.Parameter`
        (e.g. nested Serializers, file fields, ...), the schema generation will fail with an error.

        Schema generation will also fail if the name of any Field on the `query_serializer` conflicts with parameters
        generated by ``filter_backends`` or ``paginator``.

    :param list[drf_yasg.openapi.Parameter] manual_parameters: a list of manual parameters to override the
        automatically generated ones

        :class:`.Parameter`\ s are identified by their (``name``, ``in``) combination, and any parameters given
        here will fully override automatically generated parameters if they collide.

        It is an error to supply ``form`` parameters when the request does not consume form-data.

    :param str operation_id: operation ID override; the operation ID must be unique across the whole API
    :param str operation_description: operation description override
    :param str operation_summary: operation summary string
    :param list[dict] security: security requirements override; used to specify which authentication mechanism
        is required to call this API; an empty list marks the endpoint as unauthenticated (i.e. removes all accepted
        authentication schemes), and ``None`` will inherit the top-level security requirements
    :param bool deprecated: deprecation status for operation
    :param responses: a dict of documented manual responses
        keyed on response status code. If no success (``2xx``) response is given, one will automatically be
        generated from the request body and http method. If any ``2xx`` response is given the automatic response is
        suppressed.

        * if a plain string is given as value, a :class:`.Response` with no body and that string as its description
          will be generated
        * if ``None`` is given as a value, the response is ignored; this is mainly useful for disabling default
          2xx responses, i.e. ``responses={200: None, 302: 'something'}``
        * if a :class:`.Schema`, :class:`.SchemaRef` is given, a :class:`.Response` with the schema as its body and
          an empty description will be generated
        * a ``Serializer`` class or instance will be converted into a :class:`.Schema` and treated as above
        * a :class:`.Response` object will be used as-is; however if its ``schema`` attribute is a ``Serializer``,
          it will automatically be converted into a :class:`.Schema`
    :type responses: dict[int or str, (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or
        drf_yasg.openapi.Response or str or rest_framework.serializers.Serializer)]

    :param list[type[drf_yasg.inspectors.FieldInspector]] field_inspectors: extra serializer and field inspectors; these
        will be tried before :attr:`.ViewInspector.field_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
    :param list[type[drf_yasg.inspectors.FilterInspector]] filter_inspectors: extra filter inspectors; these will be
        tried before :attr:`.ViewInspector.filter_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
    :param list[type[drf_yasg.inspectors.PaginatorInspector]] paginator_inspectors: extra paginator inspectors; these
        will be tried before :attr:`.ViewInspector.paginator_inspectors` on the :class:`.inspectors.SwaggerAutoSchema`
    :param list[str] tags: tags override
    :param extra_overrides: extra values that will be saved into the ``overrides`` dict; these values will be available
        in the handling :class:`.inspectors.SwaggerAutoSchema` instance via ``self.overrides``
    c                    s„  t ‡fdd„tjD ƒƒr tdƒ‚ˆˆˆ
ˆˆˆˆˆˆˆ	r>tˆ	ƒnd ˆrLtˆƒnd ˆrZtˆƒnd ˆrhtˆƒnd dœ‰tˆƒ‰ˆtk	rˆˆˆd< ˆ ˆ¡ ˆsšˆS tˆdg ƒ}tˆdi ƒ}‡fdd	„| 	¡ D ƒ}|| }tˆd
d ƒ‰‡fdd	„tˆdg ƒD ƒ}|| ‰ tˆdi ƒ‰ˆ}ˆ�sˆ�r¶ˆ �s(tdƒ‚t
ˆƒt
ˆƒk�sBtdƒ‚tˆtƒ�rVtdƒ‚ˆ�rhˆ ¡ g}ndd	„ ˆD ƒ}t‡ fdd„|D ƒƒ�s–tdƒ‚t ‡fdd„|D ƒƒ�r¶tdƒ‚ˆ �r^t
|ƒt
|ƒk�sÖtdƒ‚tˆ ƒdk�rô|�sþtdƒ‚n
|�püˆ }t ‡fdd„|D ƒƒ�rtdƒ‚t ‡fdd„|D ƒƒ�r>tdƒ‚ˆ ‡fdd„|D ƒ¡ ˆˆ_n"|�rltdƒ‚ˆ�rztdƒ‚ˆˆ_ˆS )Nc                 3   s   | ]}|ˆ kV  qd S ©Nr   )Ú.0Zhm)Úextra_overridesr   r   Ú	<genexpr>r   s     z9swagger_auto_schema.<locals>.decorator.<locals>.<genexpr>z"HTTP method names not allowed here)Úrequest_bodyÚquery_serializerÚmanual_parametersÚoperation_idÚoperation_summaryÚ
deprecatedÚoperation_descriptionÚsecurityÚ	responsesÚfilter_inspectorsÚpaginator_inspectorsÚfield_inspectorsÚtagsÚauto_schemaÚbind_to_methodsÚmappingc                    s   g | ]\}}|ˆ j kr|‘qS r   )r   )r   ÚmthÚname)Úview_methodr   r   Ú
<listcomp>�   s     
 z:swagger_auto_schema.<locals>.decorator.<locals>.<listcomp>Úclsc                    s   g | ]}t ˆ |ƒr|‘qS r   )Úhasattr)r   Úm©Úview_clsr   r   r5   ’   s     
 Úhttp_method_namesÚ_swagger_auto_schemazI`method` or `methods` can only be specified on @action or @api_view viewsz specify either method or methodszR`methods` expects to receive a list of methods; use `method` for a single argumentc                 S   s   g | ]}|  ¡ ‘qS r   ©Úlower©r   r2   r   r   r   r5       s     c                 3   s   | ]}|ˆ kV  qd S r   r   r?   )Úavailable_http_methodsr   r   r!   ¡   s     zhttp method not bound to viewc                 3   s   | ]}|ˆ kV  qd S r   r   r?   ©Úexisting_datar   r   r!   ¢   s     z"http method defined multiple timeszthis should never happenr   z�on multi-method api_view or action, you must specify swagger_auto_schema on a per-method basis using one of the `method` or `methods` argumentsc                 3   s    | ]}t tˆ |d ƒdƒV  qd S )Nr<   )r7   Úgetattrr?   r9   r   r   r!   °   s     z+swagger_auto_schema applied twice to methodc                 3   s   | ]}|ˆ kV  qd S r   r   r?   rA   r   r   r!   ²   s     c                 3   s   | ]}|  ¡ ˆ fV  qd S r   r=   r?   )Údatar   r   r!   ³   s     z±the methods argument should only be specified when decorating an action; you should also ensure that you put the swagger_auto_schema decorator AFTER (above) the _route decorator)Úanyr   r;   ÚAssertionErrorÚlistÚfilter_noner   ÚupdaterC   ÚitemsÚboolÚ
isinstanceÚstrr>   ÚallÚlenr<   )r4   r0   r1   Zmapping_methodsZaction_http_methodsZapi_view_http_methodsZ_methods©r/   r'   r    r-   r+   r$   ÚmethodÚmethodsr(   r%   r&   r,   r#   r"   r*   r)   r.   )r@   rD   rB   r:   r4   r   Ú	decoratorq   st     ó
  ÿ
ÿ ÿz&swagger_auto_schema.<locals>.decoratorr   )rQ   rR   r/   r"   r#   r$   r%   r(   r&   r)   r'   r*   r-   r+   r,   r.   r    rS   r   rP   r   Úswagger_auto_schema!   s    P,NrT   c                    s   ‡ fdd„}|S )zà
    Decorates the method of a serializers.SerializerMethodField
    to hint as to how Swagger should be generated for this field.

    :param serializer_or_field: ``Serializer``/``Field`` class or instance
    :return:
    c                    s
   ˆ | _ | S r   )Z_swagger_serializer)Zserializer_method©Úserializer_or_fieldr   r   rS   Ë   s    z,swagger_serializer_method.<locals>.decoratorr   )rV   rS   r   rU   r   Úswagger_serializer_methodÂ   s    	rW   c                 C   s¶   t |ddƒ}t ||dƒp|}t |ddƒ}t |ddƒ}|dksL|dksL|dkrPd	S |d
ksh|d	ksh|dkrldS t|tƒrzd	S t|tttfƒrŽdS |  d¡ d¡}|r²d|d kr²dS d	S )zåCheck if the given path/method appears to represent a list view (as opposed to a detail/instance view).

    :param str path: view path
    :param str method: http method
    :param APIView view: target view
    :rtype: bool
    ÚactionÚ NÚdetailÚsuffix)rG   ÚcreateFÚListT)ÚretrieverI   Zpartial_updateÚdestroyZInstanceú/Ú{éÿÿÿÿ)rC   rL   r	   r
   r   r   ÚstripÚsplit)ÚpathrQ   ÚviewrX   rZ   r[   Zpath_componentsr   r   r   Úis_list_viewÓ   s     	
rg   c                 C   s&   | dkrt jS | dkrt jS t jS d S )NÚpostÚdelete)r   ZHTTP_201_CREATEDZHTTP_204_NO_CONTENTZHTTP_200_OK)rQ   r   r   r   Úguess_response_status÷   s
    rj   c                 C   s.   t dd„ | D ƒƒ}t|ƒt| ƒks*tdƒ‚|S )a²  Transform a list of :class:`.Parameter` objects into an ``OrderedDict`` keyed on the ``(name, in_)`` tuple of
    each parameter.

    Raises an ``AssertionError`` if `parameters` contains duplicate parameters (by their name + in combination).

    :param list[drf_yasg.openapi.Parameter] parameters: the list of parameters
    :return: `parameters` keyed by ``(name, in_)``
    :rtype: dict[(str,str),drf_yasg.openapi.Parameter]
    c                 s   s   | ]}|j |jf|fV  qd S r   )r3   Zin_)r   Úparamr   r   r   r!   
  s     z&param_list_to_odict.<locals>.<genexpr>zduplicate Parameters found)r   rO   rF   )Ú
parametersÚresultr   r   r   Úparam_list_to_odict   s    
rn   c                 C   s"   t | ƒ} |  t |ƒ¡ t|  ¡ ƒS )a  Merge `overrides` into `parameters`. This is the same as appending `overrides` to `parameters`, but any element
    of `parameters` whose ``(name, in_)`` tuple collides with an element in `overrides` is replaced by it.

    Raises an ``AssertionError`` if either list contains duplicate parameters.

    :param list[drf_yasg.openapi.Parameter] parameters: initial parameters
    :param list[drf_yasg.openapi.Parameter] overrides: overriding parameters
    :return: merged list
    :rtype: list[drf_yasg.openapi.Parameter]
    )rn   rI   rG   Úvalues)rl   Z	overridesr   r   r   Úmerge_params  s    rp   c                 C   sx   | dkrdS d}t | tƒr4t| ƒdd„ |  ¡ D ƒƒ}t | ttfƒrXt| ƒdd„ | D ƒƒ}|dk	rtt|ƒt| ƒkrt|S | S )z¬Remove ``None`` values from tuples, lists or dictionaries. Return other objects as-is.

    :param obj: the object
    :return: collection with ``None`` values removed
    Nc                 s   s*   | ]"\}}|d k	r|d k	r||fV  qd S r   r   )r   ÚkÚvr   r   r   r!   )  s       zfilter_none.<locals>.<genexpr>c                 s   s   | ]}|d k	r|V  qd S r   r   )r   rr   r   r   r   r!   +  s      )rL   ÚdictÚtyperJ   rG   ÚtuplerO   )ÚobjZnew_objr   r   r   rH     s    
rH   c                 C   sL   t  | ¡r*t| tjƒs$td| j ƒ‚| ƒ S t| tjƒsHtdt| ƒj ƒ‚| S )aY  Force `serializer` into a ``Serializer`` instance. If it is not a ``Serializer`` class or instance, raises
    an assertion error.

    :param serializer: serializer class or instance
    :type serializer: serializers.BaseSerializer or type[serializers.BaseSerializer]
    :return: serializer instance
    :rtype: serializers.BaseSerializer
    úSerializer required, not %sú-Serializer class or instance required, not %s©	ÚinspectÚisclassÚ
issubclassr   ZBaseSerializerrF   r   rL   rt   ©Ú
serializerr   r   r   Úforce_serializer_instance1  s    	
ÿr   c                 C   sZ   | dkrdS t  | ¡r4t| tjƒs0td| j ƒ‚| S t| tjƒsRtdt| ƒj ƒ‚t| ƒS )a5  Given a ``Serializer`` class or intance, return the ``Serializer`` class. If `serializer` is not a ``Serializer``
    class or instance, raises an assertion error.

    :param serializer: serializer class or instance, or ``None``
    :return: serializer class
    :rtype: type[serializers.BaseSerializer]
    Nrw   rx   ry   r}   r   r   r   Úget_serializer_classC  s    
ÿr€   c                 C   sZ   | pg } g }| D ]D}t  |¡r8|r,t||ƒrT| |¡ q|rFt||ƒr| t|ƒ¡ q|S )at  Given a list of instances or class objects, return the list of their classes.

    :param classes_or_instances: mixed list to parse
    :type classes_or_instances: list[type or object]
    :param expected_base_class: if given, only subclasses or instances of this type will be returned
    :type expected_base_class: type
    :return: list of classes
    :rtype: list
    )rz   r{   r|   ÚappendrL   rt   )Zclasses_or_instancesZexpected_base_classrm   rv   r   r   r   Úget_object_classesW  s    

r‚   c                 C   sJ   t | ƒ} dd„ | D ƒ} dd„ | p"g D ƒ}dd„ |D ƒ}t|ƒdkrF|S |S )a  Extract ``consumes`` MIME types from a list of parser classes.

    :param list parser_classes: parser classes
    :type parser_classes: list[rest_framework.parsers.BaseParser or type[rest_framework.parsers.BaseParser]]
    :return: MIME types for ``consumes``
    :rtype: list[str]
    c                 S   s   g | ]}t |tƒs|‘qS r   )r|   r   )r   Zpcr   r   r   r5   w  s     
 z get_consumes.<locals>.<listcomp>c                 S   s   g | ]
}|j ‘qS r   ©Ú
media_type)r   Úparserr   r   r   r5   x  s     c                 S   s   g | ]}t |ƒs|‘qS r   r   )r   Úencodingr   r   r   r5   y  s      r   )r‚   rO   )Zparser_classesÚmedia_typesZnon_form_media_typesr   r   r   Úget_consumesn  s    rˆ   c                 C   s,   t | ƒ} dd„ | pg D ƒ}dd„ |D ƒ}|S )a/  Extract ``produces`` MIME types from a list of renderer classes.

    :param list renderer_classes: renderer classes
    :type renderer_classes: list[rest_framework.renderers.BaseRenderer or type[rest_framework.renderers.BaseRenderer]]
    :return: MIME types for ``produces``
    :rtype: list[str]
    c                 S   s   g | ]
}|j ‘qS r   rƒ   )r   Zrendererr   r   r   r5   �  s     z get_produces.<locals>.<listcomp>c                    s(   g | ] ‰ t ‡ fd d„tjD ƒƒsˆ ‘qS )c                 3   s   | ]}|ˆ kV  qd S r   r   )r   Zexcluded©r†   r   r   r!   ‘  s     z*get_produces.<locals>.<listcomp>.<genexpr>)rE   r   ZEXCLUDED_MEDIA_TYPES)r   r   r‰   r   r5   �  s    ÿ)r‚   )Zrenderer_classesr‡   r   r   r   Úget_produces†  s    rŠ   c                 C   s,   t | tjƒst | tjƒr(t| dtjƒ S dS )zÄReturns true if ``field`` is a django-rest-framework DecimalField and its ``coerce_to_string`` attribute or the
    ``COERCE_DECIMAL_TO_STRING`` setting is set to ``False``.

    :rtype: bool
    Zcoerce_to_stringF)rL   r   ZDecimalFieldr   rC   Úrest_framework_settingsZCOERCE_DECIMAL_TO_STRING)Úfieldr   r   r   Údecimal_as_float•  s    r�   c                 C   sx   t | ddƒ}t| ƒj}t|dƒr(|j}nL|dkrTt| tjƒrTt 	dt
| ƒ ¡ d}n |}| d¡rt|dtdƒ … }|S )zëGet serializer's ref_name (or None for ModelSerializer if it is named 'NestedSerializer')

    :param serializer: Serializer instance
    :return: Serializer's ``ref_name`` or ``None`` for inline serializer
    :rtype: str or None
    ZMetaNÚref_nameZNestedSerializerzDForcing inline output for ModelSerializer named 'NestedSerializer':
Ú
Serializer)rC   rt   r   r7   rŽ   rL   r   ZModelSerializerÚloggerÚdebugrM   ÚendswithrO   )r~   Zserializer_metaZserializer_namerŽ   r   r   r   Úget_serializer_ref_name   s    


r“   úutf-8FÚstrictc                 C   s8   | dk	r4t | |||ƒ} t| ƒtkr*d|  } t | ¡} | S )zi
    Force `s` into a ``str`` instance.

    Fix for https://github.com/axnsan12/drf-yasg/issues/159
    NrY   )r   rt   rM   ÚtextwrapÚdedent)Úsr†   Zstrings_onlyÚerrorsr   r   r   Úforce_real_strµ  s    
rš   c                 C   sD   |   |¡}t|tƒr.t| ƒr&t|ƒ}nt|ƒ}t tj|t	j
d�¡S )zøConvert a python value related to a field (default, choices, etc.) into its OpenAPI-compatible representation.

    :param serializers.Field field: field associated with the value
    :param object value: value
    :return: the converted value
    )r6   )Zto_representationrL   r   r�   ÚfloatrM   r   ÚloadsÚdumpsr   ÚJSONEncoder)rŒ   Úvaluer   r   r   Úfield_value_to_representationÆ  s    


r    c                 C   sÐ   t | dtjƒ}|tjk	rÌt|ƒr€z4t|dƒr6| | ¡ t |ddƒrL|| ƒ}n|ƒ }W n* tk
r~   tjd| dd� tj}Y nX |tjk	rÌ|dk	rÌzt	| |ƒ}W n* tk
rÊ   tjd	| dd� tj}Y nX |S )
z±
    Get the default value for a field, converted to a JSON-compatible value while properly handling callables.

    :param field: field instance
    :return: default value
    ÚdefaultÚset_contextZrequires_contextFzfdefault for %s is callable but it raised an exception when called; 'default' will not be set on schemaT)Úexc_infoNzX'default' on schema for %s will not be set because to_representation raised an exception)
rC   r   ÚemptyÚcallabler7   r¢   Ú	Exceptionr�   Úwarningr    )rŒ   r¡   r   r   r   Úget_field_defaultÙ  s2    




 ÿ ÿr¨   c                 C   s   t jdkrt| tƒS t| tƒS )z�Check if a given object is a dict that maintains insertion order.

    :param obj: the dict object to check
    :rtype: bool
    )é   é   )ÚsysÚversion_inforL   rs   r   )rv   r   r   r   Údict_has_ordered_keysú  s    

r­   )N)r”   Fr•   ):rz   Úloggingr«   r–   Úcollectionsr   Údecimalr   Z	django.dbr   Zdjango.utils.encodingr   Zrest_frameworkr   r   Zrest_framework.mixinsr   r	   r
   r   Zrest_framework.parsersr   Zrest_framework.requestr   Zrest_framework.settingsr   r‹   Zrest_framework.utilsr   r   Zrest_framework.viewsr   Zapp_settingsr   Ú	getLoggerr   r�   Úobjectr   r   rT   rW   rg   rj   rn   rp   rH   r   r€   r‚   rˆ   rŠ   r�   r“   rš   r    r¨   r­   r   r   r   r   Ú<module>   sb   

        ý
 "$	

!