A version of Python's urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values.
(query, doseq=False)
| 43 | |
| 44 | |
| 45 | def urlencode(query, doseq=False): |
| 46 | class="st">""" |
| 47 | A version of Python&class="cm">#x27;s urllib.parse.urlencode() function that can operate on |
| 48 | MultiValueDict and non-string values. |
| 49 | class="st">""" |
| 50 | if isinstance(query, MultiValueDict): |
| 51 | query = query.lists() |
| 52 | elif hasattr(query, class="st">"items"): |
| 53 | query = query.items() |
| 54 | query_params = [] |
| 55 | for key, value in query: |
| 56 | if value is None: |
| 57 | raise TypeError( |
| 58 | class="st">"Cannot encode None for key &class="cm">#x27;%s' in a query string. Did you " |
| 59 | class="st">"mean to pass an empty string or omit the value?" % key |
| 60 | ) |
| 61 | elif not doseq or isinstance(value, (str, bytes)): |
| 62 | query_val = value |
| 63 | else: |
| 64 | try: |
| 65 | itr = iter(value) |
| 66 | except TypeError: |
| 67 | query_val = value |
| 68 | else: |
| 69 | class="cm"># Consume generators and iterators, when doseq=True, to |
| 70 | class="cm"># work around https://bugs.python.org/issue31706. |
| 71 | query_val = [] |
| 72 | for item in itr: |
| 73 | if item is None: |
| 74 | raise TypeError( |
| 75 | class="st">"Cannot encode None for key &class="cm">#x27;%s' in a query " |
| 76 | class="st">"string. Did you mean to pass an empty string or " |
| 77 | class="st">"omit the value?" % key |
| 78 | ) |
| 79 | elif not isinstance(item, bytes): |
| 80 | item = str(item) |
| 81 | query_val.append(item) |
| 82 | query_params.append((key, query_val)) |
| 83 | return original_urlencode(query_params, doseq) |
| 84 | |
| 85 | |
| 86 | def http_date(epoch_seconds=None): |