Jim Bell Jim Bell - 1 year ago 72
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:

import os

virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/'
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
# 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)
ctype = 'text/html'
myVar = "Howdy Partner"
response_body = '''<!doctype html>
<html lang="en">


<h1> My Change - Hello World!</h1>


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

Answer Source

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">


  <h1> My Change - Hello World!</h1>

</html>''' %myVar
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download