Jim Bell Jim Bell - 5 months ago 14
HTML Question

HTML variable inside Python code won't display

I'm having trouble inserting a variable into my html code which is inside python. The error exists with the code %(myVar). If I remove %(myVar) then the website display %s. When I insert %(myVar) then I get a 500 Internal Sever Error.

Below is my code:

#!/usr/bin/python
import os

virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
pass
#
# IMPORTANT: Put any additional includes below this line. If placed above this
# line, it's possible required libraries won't be in your searchable path
#
import time
def application(environ, start_response):

ctype = 'text/plain'
if environ['PATH_INFO'] == '/health':
response_body = "1"
elif environ['PATH_INFO'] == '/env':
response_body = ['%s: %s' % (key, value)
for key, value in sorted(environ.items())]
response_body = '\n'.join(response_body)
else:
ctype = 'text/html'
myVar = "Howdy Partner"
response_body = '''<!doctype html>
<html lang="en">

<body>

<h1> My Change - Hello World!</h1>
<p1>%s</p1>

</body>
</html>'''

%(myVar )
status = '200 OK'
response_headers = [('Content-Type', ctype), ('Content-Length', str(len(response_body)))]
#
start_response(status, response_headers)
return [response_body]

Answer

You need to have %myvar on the same line than the end of your string otherwise you get a Syntax error because %(myVar ) is not a statement.

     response_body = '''<!doctype html>
<html lang="en">

<body>

  <h1> My Change - Hello World!</h1>
  <p1>%s</p1>

</body>
</html>''' %myVar
Comments