我的任务有两个输入
>>> uri = u'/shop/amazonwow/getstates/1'
>>> uri_regex = u'/shop/(?P<shopid>.+)$/getstates/(?P<countryid>.+)$/'
这里uri
是请求网址,我也传递了一个uri模式(uri_regex)。
我需要从uri获取所有动态数据。我们将根据我们的uri_regex确定哪些数据是动态的
示例:这里uri_regex将shopid,countryid作为正则表达式模式,url在相同索引处的值为“amazonwow,1”。
我的输出将是:
out = {'shopid': 'amazonwow', 'countryid' :1,}
我的尝试:
>>> uri_list = uri.split('/')
[u'', u'shop', u'amazonwow', u'getstates', u'1']
>>> regex = uri_regex.split('/')
>>> regex
[u'', u'shop', u'(?P<shopid>.+)$', u'getstates', u'(?P<countryid>.+)$']
>>> out = {}
>>> for i in range(len(regex)):
if regex[i].startswith('(?') & regex[i].endswith(')$'):
key = regex[i][regex[i].find("<")+1:regex[i].find(">")]
out[key] = uri_list[i]
>>> print out
{u'shopid': u'amazonwow', u'countryid': u'1'}
>>>
注意:我试过这个,但我不认为这是上述问题的正确解决方案。如果你们有更好的方法,请指导我。
答案 0 :(得分:0)
import re
uri = u'/shop/amazonwow/getstates/1'
pattern = re.compile(u'shop/(.+)/getstates/(.+)')
if pattern.search(uri):
out['shopid'] = pattern.search(uri).groups()[0]
out['countryid'] = pattern.search(uri).groups()[1]
输出:
out = {'countryid': '1', 'shopid': 'amazonwow'}
答案 1 :(得分:0)
我的尝试:
def fetch_uri_variables(uri, uri_regex):
"""
function to fetch dynamic variables passed in uri as per
regular expression defined into uri_regex
"""
out, uri_list, uri_regex = {}, uri.split('/'), uri_regex.split('/')
for pattern in range(len(uri_regex)):
if re.search('^(\(\?)(.*)(\)\$)$', uri_regex[pattern]):
out[re.search('\<(.*)\>', uri_regex[pattern]).group(1)] = \
uri_list[pattern]
return out
>>> uri
u'/testing/shop/amazonwow/getstates/1'
>>> uri_regex
u'/(?P<test>.+)$/shop/(?P<shopid>.+)$/getstates/(?P<countryid>.+)$/'
>>> fetch_uri_variables(uri, uri_regex)
{u'test': u'testing', u'countryid': u'1', u'shopid': u'amazonwow'}
>>>