How to send parameters to html file I am serving through Klein(Flask) application?

388 Views Asked by At

I am using Klein to develop REST endpoints. (similar to Python Flask) I am interested in how can I pass parameters to the HTML file I want to serve, if that is even possible.

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)
2

There are 2 best solutions below

0
On

Use a templating language such as Jinja or Chameleon. You could return a dictionary and interact with the dictionary on the template.

Klein's docs describe how to use Twisted templates.

Templates

You can also make easy use of twisted.web.templates by returning anything that implements twisted.web.template.IRenderable such as twisted.web.template.Element in which case the template will be rendered and the result will be sent as the response body.

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)

and this, which shows you exactly what you are asking for. To quote the first few paragraphs:

HTML templating is the process of transforming a template document (one which describes style and structure, but does not itself include any content) into some HTML output which includes information about objects in your application. There are many, many libraries for doing this in Python: to name a few, jinja2 , django templates , and clearsilver . You can easily use any of these libraries in your Twisted Web application, either by running them as WSGI applications or by calling your preferred templating system’s APIs to produce their output as strings, and then writing those strings to Request.write .

Before we begin explaining how to use it, I’d like to stress that you don’t need to use Twisted’s templating system if you prefer some other way to generate HTML. Use it if it suits your personal style or your application, but feel free to use other things. Twisted includes templating for its own use, because the twisted.web server needs to produce HTML in various places, and we didn’t want to add another large dependency for that. Twisted is not in any way incompatible with other systems, so that has nothing to do with the fact that we use our own.

0
On

See this sample for use Jinja2 templates with Klein.