Use instead of + for space in python query parameters

前端 未结 7 1284
猫巷女王i
猫巷女王i 2021-02-03 23:30

I have written the following python script, using python requests (http://requests.readthedocs.org/en/latest/):

import requests

payload = {\'key1\': \'value  1\         


        
7条回答
  •  -上瘾入骨i
    2021-02-03 23:46

    from urllib.parse import urlencode
    
    def to_query_string(params):
        return urlencode(params, doseq=True).replace('+', '%20')
    

    You could pass a string to params instead of a dictionary, and manually handle the spaces.

    Maybe something along the lines of

    def to_query_string(p, s=''):
        for k in p:
            v = p[k]
            if isinstance(v, str):
                s += f'{k}={v}&'.replace(' ', '%20')
            elif isinstance(v, int):
                s += f'{k}={v}&'
            elif isinstance(v, list):
                for i in v:
                    s += f'{k}={i}&'
        return s[:-1]  # remove last '&'
    
    which can be used as
    min = 10
    max = 30
    params = {'query': f'score between {min} and {max}', 'limit': 1, 'information': ['name', 'location']}
    response = get('/api/dogs', params=to_query_string(params))
    

提交回复
热议问题