3 ÅýP\¡ ã@sDdZddlmZddlmZd Zdd„Zdd„Zdd „Zd d „Zd S)z8Implementation of nested form-data encoding function(s).é)Ú basestring)Ú urlencodercsdtttf‰t|ƒ}tdd„|Dƒƒs,tdƒ‚|}x"t‡fdd„|DƒƒrRt|ƒ}q2Wt|f|ž|ŽS)aTHandle nested form-data queries and serialize them appropriately. There are times when a website expects a nested form data query to be sent but, the standard library's urlencode function does not appropriately handle the nested structures. In that case, you need this function which will flatten the structure first and then properly encode it for you. When using this to send data in the body of a request, make sure you specify the appropriate Content-Type header for the request. .. code-block:: python import requests from requests_toolbelt.utils import formdata query = { 'my_dict': { 'foo': 'bar', 'biz': 'baz", }, 'a': 'b', } resp = requests.get(url, params=formdata.urlencode(query)) # or resp = requests.post( url, data=formdata.urlencode(query), headers={ 'Content-Type': 'application/x-www-form-urlencoded' }, ) Similarly, you can specify a list of nested tuples, e.g., .. code-block:: python import requests from requests_toolbelt.utils import formdata query = [ ('my_list', [ ('foo', 'bar'), ('biz', 'baz'), ]), ('a', 'b'), ] resp = requests.get(url, params=formdata.urlencode(query)) # or resp = requests.post( url, data=formdata.urlencode(query), headers={ 'Content-Type': 'application/x-www-form-urlencoded' }, ) For additional parameter and return information, see the official `urlencode`_ documentation. .. _urlencode: https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode css|]}t|ƒVqdS)N)Ú _is_two_tuple)Ú.0Úi©rú/usr/lib/python3.6/formdata.pyú Nszurlencode..zQExpected query to be able to be converted to a list comprised of length 2 tuples.c3s|]\}}t|ˆƒVqdS)N)Ú isinstance)rÚ_Úv)Úexpand_classesrrr Ss) ÚdictÚlistÚtupleÚ _to_kv_listÚallÚ ValueErrorÚanyÚ_expand_query_valuesÚ _urlencode)ZqueryÚargsÚkwargsÚoriginal_query_listÚ query_listr)r rr sA  cCst|dƒrt|jƒƒS|S)NÚitems)Úhasattrrr)Z dict_or_listrrrrYs  rcCst|ttfƒot|ƒdkS)Nr)r rrÚlen)Úitemrrrr_srcs\g}xR|D]J\}}t|tƒr,|j||fƒq |d‰t|ƒ}|j‡fdd„|Dƒƒq W|S)Nz[%s]c3s|]\}}ˆ||fVqdS)Nr)rÚkr )Úkey_fmtrrr ksz'_expand_query_values..)r rÚappendrÚextend)rrÚkeyÚvalueZ value_listr)r rrcs rN)r) Ú__doc__Z_compatrrrÚ__all__rrrrrrrÚs  O