0

Looking for an elegant way to create a URL by reading in values from a config file.

If I have the following three fields in a config file:

query1=
query2=
query3=

And I want to add them to a BASE_URL if they exist, what is an elegant way to do this?

I know there is an ugly answer like:

url +='?query1={}'.format(param1) if param1 and Not param2 or param3
url +='?query1={}&query2={}'.format(param1,param2) if param1 and param2 and Not param3
etc...

Is there an elegant pythonic solution to this? A way to abstract this idea? Thank you.

2 Answers 2

1

Store the fields in a dictionary as "key:value" pairs (you can read the file as dictionary using CSV reader) and append them to the base URL if needed:

fields = {'query1' : 'value1', 'query2' : '', 'query3' : 5, ...}
if fields: # Avoid null fields
    url += '?' + '&'.join('{}={}'.format(k,v) for k,v in fields.items() if v)
# '...?query1=value1&query3=5'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I think I personally prefer this way. Cheers.
1

One way to do this, if you're a fan of list comprehensions like I am:

params = [param1,param2,param3]

query_array = ['query%d=%s'%(ii+1,param) for ii,param in enumerate(params) if param]
url += '?'+'&'.join(query_array)

This will eliminate the need to check all the params individually to see if they exist

1 Comment

You need a '?' before the parameters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.