I want to store a number of url patterns in my django model which a user can provide parameters to which will create a url.
For example I might store these 3 urls in my db where %s is the variable parameter provided by the user:
- www.thisissomewebsite.com?param=%s
- www.anotherurl/%s/
- www.lastexample.co.uk?param1=%s&fixedparam=2
As you can see from these examples the parameter can appear anywhere in the string and not in a fixed position.
I have 2 models, one holds the urls and one holds the variables:
class URLPatterns(models.Model):
pattern = models.CharField(max_length=255)
class URLVariables(models.Model):
pattern = models.ForeignKey(URLPatterns)
param = models.CharField(max_length=255)
What would be the best way to generate these urls by replacing the %s with the variable in the database.
would it just be a simple replace on the string e.g:
urlvariable = URLVariable.objects.get(pk=1)
pattern = url.pattern
url = pattern.replace("%s", urlvariable.param)
or is there a better way?
EDIT It would also be nice if the user could choose to store either a sin开发者_StackOverflowgle variable or a list of variables which would then replace a number of variables in the string e.g.
u = URLPatterns(pattern='www.url?param=%s¶m2=%s¶m3=%s')
v = URLVariables(pattern=u, param='[2,6,3]')
url = SOME WAY TO REPLACE THE 3 %s WITH THE 3 VARIABLES IN THE ARRAY (this would need to be converted from a string in someway)
Thanks
ast.literal_eval()
can be used to parse a string into a Python value or structure. If it's a list
then just pass it to tuple()
before using string interpolation.
>>> param = [2, 6, 3]
>>> pattern = 'www.url?param=%s¶m2=%s¶m3=%s'
>>> url = pattern % tuple(param)
>>> url
'www.url?param=2¶m2=6¶m3=3'
if param is a string like '[2,6,3]' you can use ast.literal_eval() or json.loads():
>>> ast.literal_eval('[2,6,3]')
[2, 6, 3]
or
>>> json.loads(param)
[2, 6, 3]
or
>>> simplejson.loads(param)
[2, 6, 3]
You can do this:
pattern="www.url?param=%s¶m2=%s¶m3=%s"
params = "[1, 2, 3]"
url = pattern % tuple(s.strip('[] ') for s in params.split(','))
or use ast.literal_eval(params)
as Ignacio suggests.
精彩评论