B #a2@sXddlmZmZddlZddlZddlZddlZddlmZddl Z ddl Z ddl Z ddl Z yddl mZWn ek rddlmZYnXddlmmZddlZddlmZmZddlmZmZmZmZy eeZ Wne!k re"Ze"Z YnXe #e$Z%ye&Z'Wne!k r&e(Z'YnXGdd d ej)Z*ydd lm+Z,Wn(ek rrGd d d ej)Z,YnXydd lm+Z+e+j-Z.Wnek re*Z.YnXe /d Z0ddZ1ddZ2ddZ3ddZ4d0ddZ5Gddde6Z7ddZ8Gddde6Z9ddZ:d d!Z;d"d#Zd(d)Z?d*d+Z@d,d-ZAGd.d/d/e6ZBdS)1) b64decode b64encodeN)Enum)quote)DictAny)ValidationErrorSerializationErrorDeserializationErrorraise_with_tracebackc@s(eZdZdZddZddZddZdS) UTCzTime Zone info for handling UTCcCs tdS)zUTF offset for UTC is 0.r)datetime timedelta)selfdtr;/tmp/pip-target-jgxl_w8r/lib/python/msrest/serialization.py utcoffsetFsz UTC.utcoffsetcCsdS)zTimestamp representation.Zr)rrrrrtznameJsz UTC.tznamecCs tjddS)zNo daylight saving for UTC.r)hours)rr)rrrrrdstNszUTC.dstN)__name__ __module__ __qualname____doc__rrrrrrrr Csr )timezonec@s@eZdZdZddZddZddZdd Zd d Zd d Z dS) _FixedOffsetzFixed offset in minutes east from UTC. Copy/pasted from Python doc :param datetime.timedelta offset: offset in timedelta format cCs ||_dS)N)_FixedOffset__offset)roffsetrrr__init__[sz_FixedOffset.__init__cCs|jS)N)r)rrrrrr^sz_FixedOffset.utcoffsetcCst|jdS)Ni)strr total_seconds)rrrrrrasz_FixedOffset.tznamecCsd|dS)Nz)formatr)rrrr__repr__dsz_FixedOffset.__repr__cCs tdS)Nr)rr)rrrrrrgsz_FixedOffset.dstcCs|jfS)N)r)rrrr__getinitargs__jsz_FixedOffset.__getinitargs__N) rrrrr!rrr%rr&rrrrrUsrz (?sz0full_restapi_key_transformer..)_FLATTENsplit)r'r(r)keysrrrfull_restapi_key_transformersr2cCst|||\}}|d|fS)zA key transformer that returns the last RestAPI key. :param str key: The attribute name :param dict attr_desc: The attribute metadata :param object value: The value :returns: The last RestAPI key. )r2)r'r(r)rrrlast_restapi_key_transformersr4cCsg}|drB|dk rBx|D] }|t|d|dd|7}qWnj|dr|dk rt|dsjtd||x@|D] }|t|d|dd|7}qtWnt|dr|S|S) N[z contentrr3{valuestype _validation) startswith_recursive_validatehasattrr r7validate) attr_name attr_typedataresultcontentrrrr;s "  " r;cCs<|r|rt|||r.td|d|St|SdS)zCreate a XML node.r6}N)ETregister_namespaceElement)tagprefixnsrrr_create_xml_nodes  rJc@seZdZdZiZiZiZddZddZddZ dd Z e d d Z e d d Z e ddZddZd%ddZdefddZe ddZe d&ddZe d'ddZe dd Ze d!d"Ze d#d$ZdS)(ModelzmMixin for all client request body/response body models to support serialization and deserialization. cKsri|_xf|D]^}||jkr,td||jq ||jkrZ|j|ddrZtd||jq t||||q WdS)Nz;%s is not a known attribute of class %s and will be ignoredreadonlyFz1Readonly attribute %s will be ignored in class %s)additional_properties_attribute_map_LOGGERwarning __class__r9getsetattr)rkwargsr-rrrr!s  zModel.__init__cCst||jr|j|jkSdS)z,Compare objects by comparing all attributes.F) isinstancerQ__dict__)rotherrrr__eq__s  z Model.__eq__cCs || S)z,Compare objects by comparing all attributes.)rX)rrWrrr__ne__sz Model.__ne__cCs t|jS)N)r"rV)rrrr__str__sz Model.__str__cCsddd|jd<dS)Nz{object})r'r8rM)rN)clsrrr$enable_additional_properties_sendingsz*Model.enable_additional_properties_sendingcCs$y |jWntk rdSXdS)NFT)_xml_mapAttributeError)r\rrr is_xml_models  zModel.is_xml_modelcCsJy |j}Wntk r"i}YnXt|d|j|dd|ddS)zCreate XML node. namerHNrI)r^r_rJrRr)r\Zxml_maprrrrJs    zModel._create_xml_nodec sg}xևfddjDD]\}}j|}|dkrB|ddkrBq|d}yPdjj|}|dk r~|tjkr~t||}tj||fj |iWn,t k r}z| |Wdd}~XYnX|t |||7}qW|S) zValidate this model recursively and return a list of ValidationError. :returns: A list of validation error :rtype: list csg|]}|t|fqSr)getattr)r,attr)rrrr.sz"Model.validate..rMr'r[r8z{}.{}N)rNr$rQr Serializer basic_typesr7serialize_basicr=r9rRr appendr;)rZvalidation_resultr>r)r(r?Z debug_nameZvalidation_errorr)rrr=s  zModel.validateFcKs"t|}|j|fd|i|S)aReturn the JSON that would be sent to azure from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. If you want XML serialization, you can pass the kwargs is_xml=True. :param bool keep_readonly: If you want to serialize the readonly attributes :returns: A dict JSON compatible object :rtype: dict keep_readonly)rd_infer_class_models _serialize)rrhrT serializerrrr serializes zModel.serializeTcKs$t|}|j|f||d|S)aReturn a dict that can be JSONify using json.dump. Advanced usage might optionaly use a callback as parameter: .. code::python def my_key_transformer(key, attr_desc, value): return key Key is the attribute name used in Python. Attr_desc is a dict of metadata. Currently contains 'type' with the msrest type and 'key' with the RestAPI encoded key. Value is the current value in this object. The string returned will be used to serialize the key. If the return type is a list, this is considered hierarchical result dict. See the three examples in this file: - attribute_transformer - full_restapi_key_transformer - last_restapi_key_transformer If you want XML serialization, you can pass the kwargs is_xml=True. :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict )key_transformerrh)rdrirj)rrhrmrTrkrrras_dicts z Model.as_dictcCsjyF|jddd}tj|}dd|jD}|j|krDtdWntk rd|j|i}YnX|S)N.rrcSs i|]\}}t|tr||qSr)rUr8)r,r-vrrr 6sz-Model._infer_class_models..zNot Autorest generated code) rrsplitsysmodulesrVitemsr ValueError Exception)r\Z str_modelsmodelsZ client_modelsrrrri1s   zModel._infer_class_modelsNcCst|}||j||dS)aCParse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong ) content_type) Deserializerrir)r\r@ry deserializerrrr deserialize>s zModel.deserializecCs4t|}|dkrtttgn||_||j||dS)aParse a dict using given key extractor return a model. By default consider key extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model :raises: DeserializationError if something went wrong N)ry)rzri(attribute_key_case_insensitive_extractor#rest_key_case_insensitive_extractor(last_rest_key_case_insensitive_extractorkey_extractorsr)r\r@rryr{rrr from_dictJs zModel.from_dictcCsNd|jkriSt|j|}x,|j|D]}|||||q,W|S)N _subtype_map)rVdictrr7update_flatten_subtype)r\r'objectsrAZ valuetyperrrr_s  zModel._flatten_subtypec Csx|jdiD]}d}t|tjsP||d}||dpL||d}nt||j ||}|r|j |krt|S| ||}y |||St k rt d||j PYqXqt d||j PqW|S)zCheck the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. Remove the polymorphic key from the initial data. rNr3z3Subtype value %s has no mapping, use base class %s.z6Discriminator %s is absent or null, use base class %s.)rVrRr1rUrDrF_get_rest_key_partspopxml_key_extractorrNrrKeyErrorrOrP)r\responserZ subtype_keyZ subtype_valueZrest_api_response_keyZflatten_mapping_typerrr _classifyhs6     zModel._classifycCs"t|j|d}dd|DS)zGet the RestAPI key of this attr, split it and decode part :param str attr_key: Attribute key must be in attribute_map. :returns: A list of RestAPI part :rtype: list r'cSsg|] }t|qSr)r+)r,Zkey_partrrrr.sz-Model._get_rest_key_parts..)r/r0rN)r\Zattr_keyZrest_split_keyrrrrszModel._get_rest_key_parts)F)N)NN)rrrrrrNr9r!rXrYrZ classmethodr]r`rJr=rlr*rnrir|rrrrrrrrrKs,     "    *rKcCs |ddS)zThis decode a key in an _attribute_map to the actual key we want to look at inside the received data. :param str key: A key string from the generated code z\.ro)replace)r'rrrr+sr+c @seZdZdZedededediZdddiZ dd d d d d ddZ ddddddddddddd Z ddddddd dd!dd"dd#dd$dd%dd&dd'dd( Z d^d*d+Z d_d,d-Zd.d/Zd0d1Zd2d3Zd4d5Zd6d7Zed8d9Zd:d;Zedd?Zed@dAZd`dBdCZdDdEZdFdGZedadHdIZedJdKZedLdMZ edNdOZ!edPdQZ"edRdSZ#edTdUZ$edVdWZ%edXdYZ&edZd[Z'ed\d]Z(d)S)brdz Request object model serializer.r"intboolfloatcCs t|S)N)r"lower)xrrrzSerializer.MonTueWedThuFriSatSun)rrJanFebMarAprMayJunJulAugSepOctNovDec) rrrrrr cCs t||kS)N)len)ryrrrrrcCs t||kS)N)r)rrrrrrrcCs||kS)Nr)rrrrrrrcCs||kS)Nr)rrrrrrrcCs||kS)Nr)rrrrrrrcCs||kS)Nr)rrrrrrrcCs t||kS)N)r)rrrrrrrcCs t||kS)N)r)rrrrrrrcCst||tj S)N)rematchUNICODE)rrrrrrrcCst|tt|kS)N)rset)rrrrrrrcCs ||dkS)Nrr)rrrrrrr) Z min_length max_lengthZminimummaximumZ minimum_exZ maximum_exZ min_itemsZ max_itemspatternuniquemultipleNcCs^tjtjtjtjtjtjtjtjtj tj |j |j |j d |_|rHt|ni|_t|_d|_dS)N) ziso-8601zrfc-1123z unix-timedurationdatetimedecimallong bytearraybase64objectz[]z{}T)rd serialize_iso serialize_rfcserialize_unixserialize_durationserialize_dateserialize_timeserialize_decimalserialize_longserialize_bytearrayserialize_base64serialize_objectserialize_iterserialize_dictserialize_typer dependenciesr2rmclient_side_validation)rclassesrrrr!s  zSerializer.__init__c Ks||d|j}|dd}|dkr&dSd}|jj}|rF|j||f|St|dsxt|j}||jkrx|j||f|Sy |d}Wn$t k r| d| }YnXi} |r| } yn|j } x`| D]R\} } | }|s|j|iddrq|dkr*| d d kr*|jdk r| |jqАyt|| } |r@n*|| | | \}} t|trd|n|g}| |d <|j| | d f|}|r| d i}|d| d }|dd}|dd}|ddr|rt||d||}| ||w|ddr|| _wt|tr(| |nt|tjrdt| dikr~|jd}t|dkrxd |d|g|_n||_| !|n t |||}t"||_| !|n\xt#|D]}||i}|}qW|}| }x2|D]*}||kr||||}||}qWWqt$k r"wYqXqWWnHt%t t&fk rr}z"d||t'|}t(t)||Wdd}~XYnX| SdS)aSerialize data into a string according to type. :param target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict :raises: SerializationError if serialization fails. rmrhFNrNis_xmlrLrMr'r[serialization_ctxtr8xmlrarHrIrcz{{{}}}{}textr^rCrrz2Attribute {} in object {} cannot be serialized. {})*rRrmrQrserialize_datar<r8rer7r setdefaultr`rJrNrur9rMrrbcopyrUlistrDrEr$rrextendrFrGr0rjoinrg unicode_strreversedrvr_ TypeErrorr"r r )r target_obj data_typerTrmrhr> class_nameis_xml_model_serialization serialized attributesrcr(Z orig_attrr1new_attrxml_descxml_nameZ xml_prefixxml_nsZ splitted_tagZ local_noder-Z unflattenedZ _new_attrZ _serializederrmsgrrrrjs                         zSerializer._serializec Ks$|dkrtddd|d}|j|d}y |d}Wn8tk rp|rht|trh|d|}nd}YnX|rt |t sy:t |j}d|_ |rt g|_n tt tg|_|||}Wn6tk r}zttdt||Wdd}~XYnX|jrt|||}|r|d |j||f|S) a Serialize data intended for a request body. :param data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict :raises: SerializationError if serialization fails. :raises: ValueError if data is None NrequiredbodyTz[]{}rFzUnable to build a model: r)r striprrRr issubclassrKrr`rUrrzadditional_properties_detectionr}rr~r _deserializer r r r"rr;rj) rr@rrTinternal_data_typerr{rerrorsrrrrFs8       $ zSerializer.bodycKsH|jrD|dk r,||jkr,|j||f|}|j||fddi|}|S)NrT)rrer7rfr=)rr@rrarTrrr_http_component_validationws z%Serializer._http_component_validationcKs|j|||f|}yN|j||f|}|dkr6t|}|ddkrNt|}ntt|dd}Wn$tk rtd ||YnX|SdS)aSerialize data intended for a URL path. :param data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str :raises: TypeError if serialization fails. :raises: ValueError if data is None r skip_quoteTr[)safez{} must be type {}.N) rrjsondumpsrRr"rr rr$)rrar@rrToutputrrrurls   zSerializer.urlc sj|||f}y|drn|ddfdd|D}ddsZdd|D}tj|fSj||f}|d krt|}dd krt|}ntt|d d }Wn$t k rt d ||Yn Xt|SdS)aSerialize data intended for a URL query. :param data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str :raises: TypeError if serialization fails. :raises: ValueError if data is None r5rr3cs(g|] }|dk r j|fndqS)Nr[)r)r,d)rrTrrrr.sz$Serializer.query..rFcSsg|]}tt|ddqS)r[)r)rr")r,rrrrr.srTr[)rz{} must be type {}.N) rr:rRr"rrrrrr rr$)rrar@rrTrr)rrTrrquerys&      zSerializer.querycKs|j|||f|}y<|dkr*dd|D}|j||f|}|dkrLt|}Wn$tk rrtd||Yn Xt|SdS)aSerialize data intended for a request header. :param data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str :raises: TypeError if serialization fails. :raises: ValueError if data is None )z[str]cSsg|]}|dkrdn|qS)Nr[r)r,rrrrr.sz%Serializer.header..rz{} must be type {}.N)rrrrr rr$r")rrar@rrTrrrrheaders zSerializer.headercKs|dd}|r&|dkr&td|dn|dkr2dS|dr@dSyBx<|D]0\}}|j|dd}|||rLt|||qLWWn tk rtd|dYnX|SdS) z6Validate that a piece of data meets certain conditionsrFNTrLcSsdS)NFr)rrrrrrrz%Serializer.validate..unknown)rRr ru validationr)r\r@rarTrr'r)Z validatorrrrr=s    zSerializer.validatec Ks|dkrtdy||jkr0|j||f|S||jkrL|j||f|S|j||j}t|t rtt j ||dS|d|d}||jkr|j|||ddf|SWn>tt fk r}zd}t t||||Wdd}~XYnX|j|f|SdS)aSerialize generic data according to supplied data type. :param data: The data to be serialized. :param str data_type: The type to be serialized from. :param bool required: Whether it's essential that the data not be empty or None :raises: AttributeError if required data is None. :raises: ValueError if data is None :raises: SerializationError if serialization fails. NzNo value for given attribute)enum_objrr3rz.Unable to serialize value: {!r} as type: {!r}.)rvrer7rfrrrRrQrrrdserialize_enumrr r r$rj)rr@rrTZ enum_type iter_typerrrrrrs&    $zSerializer.serialize_datacKs6|di|}|r|S|ddr2|j|SdS)NZbasic_types_serializersrF)rR_xml_basic_types_serializers)r\rrTcustom_serializerrrr_get_custom_serializerss  z"Serializer._get_custom_serializerscKs8|j|f|}|r||S|dkr,||St||S)aSerialize basic builting data type. Serializes objects to str, int, float or bool. Possible kwargs: - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers :param data: Object to be serialized. :param str data_type: Type of object in the iterable. r")r serialize_unicodeeval)r\r@rrTr rrrrfs  zSerializer.serialize_basiccCsTy|jStk rYnXyt|tr,|SWntk rFt|SXt|SdS)zSpecial handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. :param data: Object to be serialized. :rtype: str N)r)r_rUunicode NameErrorr")r\r@rrrr ,s  zSerializer.serialize_unicodec Ksft|trtd|di}|dd}g}xF|D]>}y||j||f|Wq4tk rp|dYq4Xq4W|rdd|D}||}d|ks|rb|di} | d } | s|d } | d d} | d | } | rt| | d d| dd} ng} x\|D]T}t|t j r|}n0t| | d d| dd}|dk rNt||_ | |qW| S|S)aSerialize iterable. Supported kwargs: - serialization_ctxt dict : The current entry of _attribute_map, or same format. serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML :param list attr: Object to be serialized. :param str iter_type: Type of object in the iterable. :param bool required: Whether the objects in the iterable must not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. :rtype: list, str z%Refuse str type as a valid iter type.rrFNcSs g|]}|dkrdnt|qS)Nr[)r")r,srrrr.asz-Serializer.serialize_iter..rrar'wrapped itemsNamerHrI) rUr"r rRrgrrvrrJrDrFr)rr@rdivrTrrrrrr is_wrappedZ node_name final_resultelZel_noderrrrCsL              zSerializer.serialize_iterc Ks|di}i}xV|D]J\}}y|j||f||||<Wqtk rbd|||<YqXqWd|kr|d}|d} t| |dd|dd} x"|D]\}}|t| |_qW| S|S)aSerialize a dictionary of objects. :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. :param bool required: Whether the objects in the dictionary must not be None or empty. :rtype: dict rNrrarHrI) rRrurr rvrJrD SubElementr) rrc dict_typerTrrr'r)rrrrrrrs&  zSerializer.serialize_dictc Ks|dkr dSt|tjr|St|}||jkrD|j||j|f|S|tkrV||S|tkrh| |S|t j kr|| |S|t j kr| |S|t jkr||S|t jkr||S|tjkr||S||jkst|tr||S|tkrZi}xX|D]L\}}y|j|f||| |<Wn$tk rNd|| |<YnXqW|S|tkrg}x>|D]6}y||j|f|Wntk rYnXqnW|St|S)aSerialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be cast to str. :param dict attr: Object to be serialized. :rtype: dict or str N) rUrDrFr8rerf _long_typerrr rrrrrrrrrDecimalrrr7rKrjrrurrvrrgr")rrcrTobj_typerr'r)objrrrrsT                    zSerializer.serialize_objectcCsy |j}Wntk r"|}YnXy |||Stk rx(|D] }|jt|krF|jSqFWd}t|||YnXdS)Nz%{!r} is not valid value for enum {!r})r)r_rvrr"r r$)rcrrA enum_valueerrorrrrrs    zSerializer.serialize_enumcKs t|S)ztSerialize bytearray into base-64 string. :param attr: Object to be serialized. :rtype: str )rdecode)rcrTrrrrszSerializer.serialize_bytearraycKs(t|d}|dddddS)znSerialize str into base-64 string. :param attr: Object to be serialized. :rtype: str ascii=+-/_)rrrr)rcrTencodedrrrrszSerializer.serialize_base64cKst|S)zpSerialize Decimal object to float. :param attr: Object to be serialized. :rtype: float )r)rcrTrrrrszSerializer.serialize_decimalcKst|S)zsSerialize long (Py2) or int (Py3). :param attr: Object to be serialized. :rtype: int/long )r)rcrTrrrr szSerializer.serialize_longcKs,t|trt|}d|j|j|j}|S)zSerialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str z{:04}-{:02}-{:02})rUr"isodate parse_dater$yearmonthday)rcrTtrrrrs  zSerializer.serialize_datecKsBt|trt|}d|j|j|j}|jr>|d|j7}|S)zSerialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str z{:02}:{:02}:{:02}z.{:02}) rUr"r& parse_timer$hourminutesecond microsecond)rcrTr+rrrr!s   zSerializer.serialize_timecKst|trt|}t|S)zSerialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str )rUr"r&parse_durationZduration_isoformat)rcrTrrrr/s  zSerializer.serialize_durationc Ksjy|jstd|}Wntk r8tdYnXdtj|j |j tj |j |j |j|j|jS)zSerialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: TypeError if format invalid. z/Datetime with no tzinfo will be considered UTC.z-RFC1123 object must be valid Datetime object.z({}, {:02} {} {:04} {:02}:{:02}:{:02} GMT)tzinforOrP utctimetupler_rr$rddaystm_wdaytm_mdaymonthstm_montm_yeartm_hourtm_mintm_sec)rcrTutcrrrr:s zSerializer.serialize_rfcc Kst|trt|}y|js&td|}|jdksB|jdkrJt dt|j  dd d dd}|rvd|}d |j|j|j|j|j|j}||d Stt fk r}zd }tt||Wd d }~XYn4tk r}zd }tt||Wd d }~XYnXd S)zSerialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str :raises: SerializationError if format invalid. z/Datetime with no tzinfo will be considered UTC.i'rzHit max or min dater0rroz#{:04}-{:02}-{:02}T{:02}:{:02}:{:02}rz$Unable to serialize datetime object.Nz.ISO-8601 object must be valid Datetime object.)rUr"r&parse_datetimer2rOrPr3r9 OverflowErrorr0rjustrstripljustr$r8r6r:r;r<rvr r r_r)rcrTr= microsecondsrrrrrrrOs,     zSerializer.serialize_isocKsRt|tr|Sy"|js tdtt|Stk rLt dYnXdS)zSerialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int :raises: SerializationError if format invalid z/Datetime with no tzinfo will be considered UTC.z/Unix time object must be valid Datetime object.N) rUrr2rOrPcalendartimegmr3r_r)rcrTrrrros zSerializer.serialize_unix)N)N)N)N))rrrrr"rrrrerr4r7rr!rjrrrrrrr=rr rfr rrr staticmethodrrrrrrrrrrrrrrrrdsZ      t1( '    C"8    rdcCs~|d}|}xfd|krrt|}t|dkr:t|d}Pt|d}|||}|dkr^dSd|dd}qW||S)Nr'rorr)r/r0rr+rRr)rcr(r@r' working_data dict_keys working_keyrrrrest_key_extractors      rKcCs|d}|}xfd|krrt|}t|dkr:t|d}Pt|d}t|d|}|dkr^dSd|dd}qW|rt|d|SdS)Nr'rorr)r/r0rr+r}r)rcr(r@r'rHrIrJrrrr~s      r~cCs"|d}t|}t|dd|S)zQExtract the attribute in "data" based on the last part of the JSON path key. r'r3N)r/r0attribute_key_extractor)rcr(r@r'rIrrrlast_rest_key_extractors rMcCs"|d}t|}t|dd|S)zExtract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" r'r3N)r/r0r})rcr(r@r'rIrrrrs rcCs ||S)N)rR)rcr$r@rrrrLsrLcCs6d}|}x|D]}||kr|}PqW||S)N)rrR)rcr$r@Z found_keyZ lower_attrr'rrrr}s  r}cCs:t|di}|d|j}|dd}|r6d||}|S)zGiven an internal type XML description, extract correct XML name with namespace. :param dict internal_type: An model type :rtype: tuple :returns: A tuple XML name + namespace dict r^rarINz{{{}}}{})rbrRrr$) internal_typeinternal_type_xml_maprrrrr _extract_name_from_internal_types    rPc Cst|trdSt|tjsdS|di}|d|d}|dd}|dd}|dd}t|d i}|d |d d} | rd | |}|d dr||S|d dr|jS|s|rt |t sd|kr| |} nP|s|rd|krt |}| |} n&|rt |} n |d|} | | } t | dkrT|rP|rLdSgSdS|r|sd| St | dkrtd|t| dSt | dkrtd|| dS)Nrrar'r8r5rF internalTyper^rIz{{{}}}{}rcrrrrzxTried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?z/Find several XML '{}' where it was not expected)rUrrDrFrRr:rbr$rrrfindallrPrr r) rcr(r@rrZ is_iter_typerrNrOrchildrenZ items_namerrrrsV                rc@s4eZdZdZedededediZe dZ d:dd Z d;d d Z d d ZddZddZdddZddZddZddZddZd d!Zed"d#Zed$d%Zed&d'Zed(d)Zed*d+Zed,d-Zed.d/Z ed0d1Z!ed2d3Z"ed4d5Z#ed6d7Z$ed8d9Z%dS)?rzzResponse object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. r"rrrzF\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?NcCsxtjtjtjtjtjtjtjtjtj tj |j |j |j d |_tjtjftjd|_|r^t|ni|_ttg|_d|_dS)N) ziso-8601zrfc-1123z unix-timerrrrrrrrz[]z{})rziso-8601T)rzdeserialize_isodeserialize_rfcdeserialize_unixdeserialize_durationdeserialize_datedeserialize_timedeserialize_decimaldeserialize_longdeserialize_bytearraydeserialize_base64deserialize_objectdeserialize_iterdeserialize_dictdeserialize_typer&ZDurationrrdeserialize_expected_typesrrrKrrr)rrrrrr!-s&   zDeserializer.__init__cCs|||}|||S)alCall the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. :raises: DeserializationError if deserialization fails. :return: Deserialized object. )_unpack_contentr)rrZ response_dataryr@rrr__call__Ns zDeserializer.__call__c CsLt|drddt|diD}yvxp|jD]b\}}||krDq2t||}|dkrXq2|d}|d}||jks2t|trq2t||| ||q2W|St k rdSX| ||\} } t| t r| || St| trt| tr||| S|dkr|Sy| j} i} x| D]\}} |dkrB| d d krBqd}| } | dd}||jkrv|j|| d <xV|jD]L}||| |}|dk r~|dk r||krd }t||||q~|}q~W| || d}|| |<qWWn>t ttfk r,}zd | }tt||Wdd}~XYnX|| |}|| | |SdS)aQCall the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. :raises: DeserializationError if deserialization fails. :return: Deserialized object. rNcSsg|]\}}|dr|qS)constant)rR)r,raconfigrrrr.fsz-Deserializer._deserialize..r9Nr8z[]{}rMr'r[rQzbIgnoring extracted value '%s' from %s for key '%s' (duplicate extraction, follow extractors order)z!Unable to deserialize to object: )r<rbrurNrrrUrrSrr__classify_target basestringdeserialize_datar8rdeserialize_enumrrrOrPrrr r _build_additional_properties_instantiate_model)rrr@ constantsrcZ mapconfigr)Z local_typerrrrZd_attrsr(Z raw_valueZ key_extractorZ found_valuerrrMrrrrZsr             zDeserializer._deserializecs~|js dSd|kr,|diddkr,dSttjrFddDdd|D}t}||}fdd|DS) NrMr'r[cSsi|]}|j|jqSr)rrG)r,rrrrrqsz=Deserializer._build_additional_properties..cSs.h|]&}|ddkrtt|ddqS)r'r[r)r+r/r0)r,descrrr sz.csi|]}||qSrr)r,r')r@rrrqs)rrRrUrDrFr7rr1)rZ attribute_mapr@Z known_keysZ present_keysZ missing_keysr)r@rrks   z)Deserializer._build_additional_propertiescCsr|dkr dSt|tr>y|j|}Wntk r<||fSXy|||j}Wntk rdYnX||jjfS)a3Check to see whether the deserialization target object can be classified into a subclass. Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. :param str/dict data: The response data to deseralize. N)NN)rUrhrrrr_rQr)rtargetr@rrrrgs  zDeserializer._classify_targetcCs,y||||dStjddddSdS)aIgnores any errors encountered in deserialization, and falls back to not deserializing the object. Recommended for use in error deserialization, as we want to return the HttpResponseError to users, and not have them deal with a deserialization error. :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deseralize. :param str content_type: Swagger "produces" if available. )ryzQRan into a deserialization error. Ignoring since this is failsafe deserializationT)exc_infoN)rOrP)rrr@ryrrrfailsafe_deserializes z!Deserializer.failsafe_deserializecCsddlm}t|di}|r8|j|kr0||jStdt|drT|||jSt|drn||j|jSt |t t fst|dr| ||S|S)aExtract the correct structure for deserialization. If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. if we can't, raise. Your Pipeline should have a RawDeserializer. If not a pipeline response and raw_data is bytes or string, use content-type to decode it. If no content-type, try JSON. If raw_data is something else, bypass all logic and return it directly. :param raw_data: Data to be processed. :param content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 r)RawDeserializercontextzGThis pipeline didn't have the RawDeserializer policy; can't deserializer_content_consumedread) Zpipeline.universalrsrbZ CONTEXT_NAMErvr<Zdeserialize_from_http_genericsrheadersrUrhbytesZdeserialize_from_text)Zraw_dataryrsrtrrrrcs"       zDeserializer._unpack_contentc s@t|rt|diyzdd|jDdd|jDfdd|D}|f|}xD]}t||||qhW|r||_|Stk r}z d||}t |t |Wdd}~XYnXnly&x |D]\}} t||| qW|St k r:} z$d }|d t || 7}t |Wdd} ~ XYnXdS) zInstantiate a response model passing in deserialized args. :param response: The response model class. :param d_attrs: The deserialized response attributes. rcSsg|]\}}|dr|qS)rL)rR)r,r-rprrrr.sz3Deserializer._instantiate_model..cSsg|]\}}|dr|qS)re)rR)r,r-rprrrr.scs*i|]"\}}|kr|kr||qSrr)r,r-rp)constrLsubtyperrrq sz3Deserializer._instantiate_model..z(Unable to deserialize {} into model {}. Nz#Unable to populate response model. zType: {}, Error: {}) callablerbr9rurSrRrMrr$r r"rwr8) rrattrsrMrTZ response_objrcrrr)expr)ryrLrzrrls0   $zDeserializer._instantiate_modelc CsN|dkr |Sy|s|S||jkr0|||S||jkrt||j|trT|Sdd}t|tj rz||rz|j szdS|j||}|S|d|d}||jkr|j|||ddS|j |}t |t rt|tj r|j }|||SWnJtttfk r<}z$d}|d||7}tt||Wdd}~XYnX|||SdS) a#Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. :raises: DeserializationError if deserialization fails. :return: Deserialized object. NcSs|dkS)N)rz[]z{}r)rrrrrJrz/Deserializer.deserialize_data..rr3rz$Unable to deserialize response data.z Data: {}, {})rer7deserialize_basicrarUrbrRtuplerDrFrrrrrjrvrr_r$r r r) rr@rZis_a_text_parsing_typeZdata_valrrrrrrrri6s8      zDeserializer.deserialize_datacsV|dkr dSt|tjr t|}t|ttfsBtdt|fdd|DS)zDeserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. :rtype: list Nz/Cannot deserialize as [{}] an object of type {}csg|]}|qSr)ri)r,a)rrrrr.qsz1Deserializer.deserialize_iter..)rUrDrFrrr r$r8)rrcrr)rrrr_as  zDeserializer.deserialize_itercsPt|trfdd|DSt|tjr8dd|D}fdd|DS)zDeserialize a dictionary. :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. :rtype: dict cs"i|]}|d|dqS)r)r')ri)r,r)rrrrrq|sz1Deserializer.deserialize_dict..cSsi|]}|j|jqSr)rrG)r,rrrrrqscsi|]\}}||qSr)ri)r,r-rp)rrrrrqs)rUrrDrFru)rrcrr)rrrr`ss   zDeserializer.deserialize_dictc Ks*|dkr dSt|tjr|St|tr2||dSt|}||jkrV|||j|S|tkrh||S|t kri}xH| D]<\}}y|j |f|||<Wq~t k rd||<Yq~Xq~W|S|t krg}x<|D]4}y||j |f|Wqt k rYqXqW|Sd}t|t|dS)zDeserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. :rtype: dict :raises: TypeError if non-builtin datatype encountered. Nr"z-Cannot deserialize generic object with type: )rUrDrFrhr~r8rerr[rrur^rvrrgrr") rrcrTrZ deserializedr'r)rrrrrr^s>        zDeserializer.deserialize_objectcCst|tjr&|j}|s&|dkr"dSdS|dkrv|dkr>t|St|trh|dkrXdS|dkrhd Std ||dkr| |St ||S) aDeserialize baisc builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as valid bool values. :param str attr: response string to be deserialized. :param str data_type: deserialization data type. :rtype: str, int, float or bool :raises: TypeError if string format is not valid. r"r[Nr)TFrr)true1T)falser>FzInvalid boolean value: {}) rUrDrFrrrhrrr$deserialize_unicoder )rrcrrrrr~s$     zDeserializer.deserialize_basiccCsFt|tr|Syt|tr|SWntk r8t|SXt|SdS)zPreserve unicode objects in Python 2, otherwise return data as a string. :param str data: response string to be deserialized. :rtype: str or unicode N)rUrr rr")r@rrrrs   z Deserializer.deserialize_unicodecCst||s|dkr|St|tr&|j}t|trlyt|j|Stk rjd}t| ||YnXy |t |St k rx&|D]}|j t | kr|SqWt d||t|SXdS)asDeserialize string into enum object. If the string is not a valid enum value it will be returned as-is and a warning will be logged. :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. :rtype: Enum Nz'{!r} is not a valid index for enum {!r}z7Deserializer is not able to find %s as valid enum in %s)rUrr)rr __members__r7 IndexErrorr r$r"rvrrOrPrzr)r@rrrrrrrjs$     zDeserializer.deserialize_enumcCst|tjr|j}tt|S)zDeserialize string into bytearray. :param str attr: response string to be deserialized. :rtype: bytearray :raises: TypeError if string format invalid. )rUrDrFrrr)rcrrrr\s z"Deserializer.deserialize_bytearraycCsNt|tjr|j}ddt|dd}||}|dddd}t|S)zDeserialize base64 encoded string into string. :param str attr: response string to be deserialized. :rtype: bytearray :raises: TypeError if string format invalid. r rrr"r!r$r#)rUrDrFrrrr)rcpaddingr%rrrr]s  zDeserializer.deserialize_base64c Cs\t|tjr|j}y t|Stjk rV}zd|}tt ||Wdd}~XYnXdS)zDeserialize string into Decimal object. :param str attr: response string to be deserialized. :rtype: Decimal :raises: DeserializationError if string format invalid. zInvalid decimal {}N) rUrDrFrrrDecimalExceptionr$r r )rcrrrrrrZ)s   z Deserializer.deserialize_decimalcCst|tjr|j}t|S)zDeserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. :rtype: long or int :raises: ValueError if string format invalid. )rUrDrFrr)rcrrrr[9s zDeserializer.deserialize_longc Csbt|tjr|j}yt|}Wn8tttfk rX}zd}t t ||Wdd}~XYnX|SdS)zDeserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. :rtype: TimeDelta :raises: DeserializationError if string format invalid. z#Cannot deserialize duration object.N) rUrDrFrr&r1rvr@r_r r )rcrrrrrrrWEs z!Deserializer.deserialize_durationcCsDt|tjr|j}td|tjtjr4td|t j |dddS)zDeserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. :rtype: Date :raises: DeserializationError if string format invalid. z[^\W\d_]z.Date must have only digits and -. Received: %sN)Z defaultmonthZ defaultday) rUrDrFrrsearchIUr r&r')rcrrrrXWs   zDeserializer.deserialize_datecCs>t|tjr|j}td|tjtjr4td|t |S)zDeserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. :rtype: datetime.time :raises: DeserializationError if string format invalid. z[^\W\d_]z.Date must have only digits and -. Received: %s) rUrDrFrrrrrr r&r,)rcrrrrYfs   zDeserializer.deserialize_timec Cst|tjr|j}yRtj|}tj|dddttj |dp@dddi}|j sb|j t d}Wn2t k r}zd }tt||Wdd}~XYnX|SdS) zDeserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. :rtype: Datetime :raises: DeserializationError if string format invalid. Nrr2rr<)minutes)tzz*Cannot deserialize to rfc datetime object.)rUrDrFremailutils parsedate_tzrrrr2 astimezoneTZ_UTCrvr r )rc parsed_datedate_objrrrrrrUts    zDeserializer.deserialize_rfcc Cs t|tjr|j}y|}tj|}|s8td|| d}t |dkrd}x$|dD]}| rr||7}q\Pq\Wt |dkr| ||dd}t |}|}|jdks|jdkrtdWn:tttfk r}zd }tt||Wd d }~XYnX|Sd S) zDeserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. :rtype: Datetime :raises: DeserializationError if string format invalid. zInvalid datetime string: rorr[rri'zHit max or min datez#Cannot deserialize datetime object.N)rUrDrFrupperrz valid_daterrvr0risdigitrr&r?r3r9r@r_r r ) rcrZ check_decimalZ decimal_strdigitrZtest_utcrrrrrrTs0         zDeserializer.deserialize_isoc Csdt|tjrt|j}ytj|t}Wn2tk rZ}zd}t t ||Wdd}~XYnX|SdS)zSerialize Datetime object into IntTime format. This is represented as seconds. :param int attr: Object to be serialized. :rtype: Datetime :raises: DeserializationError if format invalid z+Cannot deserialize to unix datetime object.N) rUrDrFrrr fromtimestamprrvr r )rcrrrrrrrVs  zDeserializer.deserialize_unix)N)N)N)N)N)&rrrrr"rrrrercompilerr!rdrrkrgrrrGrcrlrir_r`r^r~rrjr\r]rZr[rWrXrYrUrTrVrrrrrz s< ! Q  - #+-&  "       %rz)NN)CrrrrErrrenumrrloggingrrsurllibr ImportError urllib.parsexml.etree.ElementTreeetree ElementTreerDr&typingrr exceptionsr r r r rhr rrr" getLoggerrrOrrrr2r rrr=rrr/r*r2r4r;rJrrKr+rdrKr~rMrrLr}rPrrzrrrrs|            r a  I