I am writing a function to generate an API url which accept multiple arguments and replicates a part of the string. The short version(which only accept one value for variable Val
) looks like this
def get_url(par,att,value, _filter):
base_url='''https://mytest.com/api/Test/''' str(par) '''?size=100000&filters=['''
url = base_url '''{"VarA" : "''' att '''", "Val":["''' value '''"], "VarB":"''' _filter '''"}]'''
return url
print(get_url('Sales',{'Year':['2020'] , "Time"}))
This will return
https://mytest.com/api/Test/Sales?size=1000&filters=[{"VarA" : "Year", "Val":["2020"], "VarB":"Time"}]
I wrote another function so that I can pass multiple variable for Val
while also replicating the filter string using the below function
def get_url(par,argv=None, _filter=None):
if argv:
att=argv
url='''https://mytest.com/api/Test/''' str(par) '''?size=100000&filters=['''
i=0
for key in att.keys():
attribute=key
attribute_value=att[attribute]
my_lst_str = '","'.join(map(str, attribute_value))
values= '"' my_lst_str '"'
if i==0:
url=url '''{"VarA" : "''' attribute '''", "Val":[''' value '''], "VarB":''' str(_filter) '''}]'''
else:url=url ''',{"VarA" : "''' attribute '''", "Val":[''' value '''], "VarB":''' str(_filter) '''}]'''
i =1
else:
url = #Some string#
return url
url = get_url('Sales',{'Loc':['USA','CAN'],'Year':["2016","2017"]},{'Country','Time'})
But what the above code returns is this
https://mytest.com/api/Test/Sales?size=1000&filters=[{"VarA" : "Loc", "Val":["USA","CAN"], "VarB":"{'Country', 'Time'}"}],{"VarA" : "Year", "Val":["2016","2017"], "VarB":"{'Country', 'Time'}"}]
My expected output is
https://mytest.com/api/Test/Sales?size=1000&filters=[{"VarA" : "Loc", "Val":["USA","CAN"], "VarB":"Country"},{"VarA" : "Year", "Val":["2020","2017"], "VarB":"Time"}]
How do I isolate element for VarB
?
CodePudding user response:
You can use your index:
from collections import OrderedDict
def get_url(par, argv=None, _filter=None):
obj_list, obj_filter = [], list(_filter)
if argv:
att = argv
url = (
"""https://mytest.com/api/Test/""" str(par) """?size=100000&filters="""
)
i = 0
for key in att.keys():
attribute = key
attribute_value = att[attribute]
obj_list.append({"VarA" : attribute, "Val": attribute_value, "VarB": obj_filter[i]})
i = 1
else:
url = "some url"
return url str(obj_list)
url = get_url(
"Sales", OrderedDict({"Loc": ["USA", "CAN"], "Year": ["2016", "2017"], "wewe": ["4", "5"]}), {"Country", "Time", "wre"}
)
print(url)
Output:
https://mytest.com/api/Test/Sales?size=100000&filters=[{'VarA': 'Loc', 'Val': ['USA', 'CAN'], 'VarB': 'wre'}, {'VarA': 'Year', 'Val': ['2016', '2017'], 'VarB': 'Time'}, {'VarA': 'wewe', 'Val': ['4', '5'], 'VarB': 'Country'}]