Search code examples
pythonurlconfigencode

How to store/encode URL with percentage % in config file?


I'm trying to manage my data by storing it under config file. I ran into issue while I was creating my file that the URL contains '%20' and it returned the following error msg:

 raise ValueError("invalid interpolation syntax in %r at "

Here is an example of my URL format (a lil bit context here: I'm using it to get API request)

https://api.abc.com/a0/asaknfalhiasfna/Test%20Name?failed=why+why+why

And this is what I had in my config.py

import configparser
config = configparser.ConfigParser()

config['ClientProd'] = {'url': 'https://api.abc.com/a0/asaknfalhiasfna/Test%20Name?failed=why+why+why',
'response': 'id'}


with open('conf.ini', 'w') as configfile:
    config.write(configfile)

Here is the reference on what I'm trying to achieve: link
How can I encode the %20 in the URL here? Any help would be greatly appreciate it, thank you in advance.


Solution

  • You can escape with another % proceeding the problematic one.

    config['ClientProd'] = {'url': 'https://api.abc.com/a0/asaknfalhiasfna/Test%%20Name?failed=why+why+why',
    'response': 'id'}
    

    Source: https://docs.python.org/3/library/configparser.html#interpolation-of-values