【问题标题】:How to send parameters to html file I am serving through Klein(Flask) application?如何将参数发送到我通过 Klein(Flask) 应用程序提供的 html 文件?
【发布时间】:2018-05-24 12:51:20
【问题描述】:

我正在使用 Klein 开发 REST 端点。 (类似于 Python Flask) 如果可能的话,我对如何将参数传递给我想要提供的 HTML 文件感兴趣。

from twisted.web.static import File
from klein import Klein
app = Klein()

@app.route('/', branch=True)
def pg_index(request):
    return File('./')

app.run("localhost", 8080)

【问题讨论】:

    标签: python rest flask klein-mvc


    【解决方案1】:

    使用模板语言,例如JinjaChameleon。您可以返回一个字典并与模板上的字典进行交互。

    Klein's docs describe how to use Twisted templates.

    模板

    您还可以通过返回来轻松使用 twisted.web.templates 任何实现了 twisted.web.template.IRenderable 的东西,例如 twisted.web.template.Element 在这种情况下模板将是 呈现,结果将作为响应正文发送。

    from twisted.web.template import Element, XMLString, renderer
    from klein import run, route
    
    class HelloElement(Element):
        loader = XMLString((
            '<h1 '
            'xmlns:t="http://twistedmatrix.com/ns/twisted.web.template/0.1"'
            '>Hello, <span t:render="name"></span>!</h1>'))
    
        def __init__(self, name):
            self._name = name
    
        @renderer
        def name(self, request, tag):
            return self._name
    
    @route('/hello/<string:name>')
    def home(request, name='world'):
        return HelloElement(name)
    
    run("localhost", 8080)
    

    this,它准确地向您展示了您的要求。引用前几段:

    HTML 模板是转换模板文档的过程 (描述风格和结构,但本身不包括 任何内容)到一些 HTML 输出中,其中包含有关 应用程序中的对象。有很多很多图书馆可以做 Python 中的 this:仅举几例,jinja2、django templates 和 清银。您可以轻松地在您的 Twisted Web 应用程序,或者将它们作为 WSGI 应用程序运行 或者通过调用您喜欢的模板系统的 API 来生成它们的 输出为字符串,然后将这些字符串写入 Request.write 。

    在我们开始解释如何使用它之前,我想强调一下, 如果你喜欢其他的,不需要使用 Twisted 的模板系统 生成 HTML 的方法。如果它适合您的个人风格或您的 应用程序,但可以随意使用其他东西。扭曲包括 模板供自己使用,因为 twisted.web 服务器需要 在各个地方生成 HTML,我们不想添加另一个 对此有很大的依赖性。 Twisted 与 其他系统,所以这与我们使用我们的 拥有。

    【讨论】:

      【解决方案2】:

      请参阅this sample 以了解与 Klein 一起使用 Jinja2 模板。

      【讨论】:

        猜你喜欢
        • 2017-11-21
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-01
        • 1970-01-01
        • 2014-12-23
        • 2021-09-20
        相关资源
        最近更新 更多