【问题标题】:Python : for loop inside wsgi scriptPython:wsgi脚本中的for循环
【发布时间】:2015-04-15 15:55:35
【问题描述】:

我想在 wsgi 脚本的 html 部分嵌入一个 forloop。

my_list=[1,2,3]
def my_function(environ,start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ['''
            <html>
                 <body>
                      for i in my_list:
                       <p>
                          i
                       </p>
                <body>
            </html>
           ''']  

如何使 python 代码在该 wsgi 响应中运行?

【问题讨论】:

  • 恭喜!你有问题吗?快点,否则你会得到很多反对票!
  • 你为什么要在字符串里面做呢?
  • 我无法在没有模板的情况下在 html 中找到使用 python 代码,这对我来说是个问题。抱歉没有 wsgi 经验。
  • 如何转义 for 循环并使其在该 html 字符串中作为 python 代码运行。
  • 你没有。在字符串之外进行。 就像在任何其他 Python 程序中一样。

标签: python wsgi


【解决方案1】:

您想要做的是模板语言或库帮助我们做的事情。由于您不想使用任何模板语言/库,因此您需要自己构建所需的字符串。对于此特定实例,您可以执行以下操作:

s = '''\
<html>
    <body>{list}
    </body>
</html>'''

item = '''
        <p>
            {0}
        </p>\
'''
print(s.format(list="".join(map(item.format, [1, 2, 3]))))

结果:

<html>
    <body>
        <p>
            1
        </p>
        <p>
            2
        </p>
        <p>
            3
        </p>
    </body>
</html>

【讨论】:

    猜你喜欢
    • 2018-07-17
    • 2012-04-16
    • 1970-01-01
    • 2022-05-17
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    相关资源
    最近更新 更多