0

i read data from my config file like this:

ip_vlan1 = "10.10.($id+100).5"
ip_vlan2 = "10.11.($id*2+1).6"
v.v...

And for each vlan, I want calculate vlan address for it, based on ID and vlan-expression:

def calculate_vlan_id(id, vlan_exp):
    ...
    return ip_addr   # string

Example:

def(3, ip_vlan1) --> result: "10.10.103.5"
def(5, ip_vlan2) --> result: "10.11.11.6"

Do you have a solution for this?

Thanks in advance, folks!

3 Answers 3

3

You could use a text templating engine. (Which is safer than using eval based tricks).

Here's an example using genshi

from genshi.template import TextTemplate
ip_vlan1 = TextTemplate("10.10.${id+100}.5")
ip_vlan2 = TextTemplate("10.11.${2*id+1}.6")
print( ip_vlan1.generate(id=3) ) # prints 10.10.103.5
print( ip_vlan2.generate(id=5) ) # prints 10.11.11.6

If you really need the calculate_vlan_id function it would look something like this:

def calculate_vlan_id(id,ip_vlan):
  return ip_vlan.generate(id=id)

Edit:

As requested here's an example using jinja2: This may not be the best way to do this, the jinja2 docs are large and confusing.

ip_vlan1 = jinja2.Template('10.10.{{id+100}}.5')
ip_vlan2 = jinja2.Template('10.11.{{2*id+1}}.6')
ip_vlan1.render(id=3)
ip_vlan2.render(id=5)

Both these methods are untested

Sign up to request clarification or add additional context in comments.

2 Comments

Nice & clear, maybe I will change my config file format to use your solution :D Do you have another option by using Jinja2 template,pls? Thanks alot!
Hi, i found it: from jinja2 import Template ip_vlan1 = Template("10.10.{{id + 100}}.5") ip_vlan1.render(id=3) Thanks you!
1
def calculate_vlan_id(id, vlan_exp):
    vlan_exp_list = vlan_exp.split(".") 
    vlan_exp_list[2].replace("$id", id);
    vlan_exp_list[2] = eval(vlan_exp_list[2])

return '.'.join(vlan_exp_list)  # string

1 Comment

Hi, the "$id" is not always in [2] position, it can be any position. And the statement 'vlan_exp_list[2] = eval(vlan_exp_list[2])' error: "SyntaxError: invalid syntax"
1

IF you are sure that you have only only 'id', then you can do it like this.

def replace(id, vlan_exp):
    vlan_exp = vlan_exp.replace('$id',str(id))
    return ".".join(map(str,map(eval,vlan_exp.split('.'))))

But that uses eval and using eval can be harmful to your program.

Comments

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.