Python format throws KeyError

Python

Python Problem Overview


The following code snippet:

template = "\                                                                                
function routes(app, model){\                                                                
  app.get('/preNew{className}', function(req, res){\                                         
    res.render('{className}'.ejs, {});\                                                      
  });\                                                                                       
});".format(className=className)

throws a KeyError:

Traceback (most recent call last):   File "createController.py", line 31, in <module>
    });".format(className=className) KeyError: '  app'

Does someone know why?

Python Solutions


Solution 1 - Python

You have a number of unescaped braces in that code. Python considers all braces to be placeholders and is trying to substitute them all. However, you have only supplied one value.

I expect that you don't want all your braces to be placeholders, so you should double the ones that you don't want substituted. Such as:

template = """                                                                  
function routes(app, model){{
  app.get('/preNew{className}', function(req, res){{
    res.render('{className}'.ejs, {{}});                                           
  }};                                                      
}});""".format(className=className)

I also took the liberty of using triple quotes for the string literal so you don't need the backslashes at the end of each line.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlowerkeyView Question on Stackoverflow
Solution 1 - PythonkindallView Answer on Stackoverflow