Python代码中的HTML变量不会显示

时间:2016-06-23 22:35:05

标签: python html openshift

我在将变量插入到python中的html代码时遇到了问题。代码%(myVar)存在错误。如果我删除%(myVar),那么网站显示%s。当我插入%(myVar)时,我得到500内部服务器错误。

以下是我的代码:

        #!/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]

1 个答案:

答案 0 :(得分:2)

您需要在与字符串结尾相同的行上放置%myvar,否则会出现语法错误,因为%(myVar )不是声明。

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

<body>

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

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