It looks like you need a template engine for serving files, you can use jinja2 for it. In your case static.File
should be used to render template directory and resource.Resource
— to serve files in it rendered via jinja2:
import os
import jinja2
from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.static import File
from twisted.web.server import Site
template_dir = '{}/templates/'.format(os.path.dirname(os.path.realpath(__file__)))
def render(template_file, context):
env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir))
return env.get_template(template_file).render(context).encode('utf-8')
class RDirectory(File):
def getChild(self, name, request):
if name == '':
return super(RDirectory, self).getChild(name, request)
return RFile()
class RFile(Resource):
isLeaf = True
def render_GET(self, request):
data = {'var': 'my variable'}
return render(request.uri, data)
if __name__ == '__main__':
web = Site(RDirectory(template_dir))
reactor.listenTCP(int(os.environ.get('SR_LISTEN_PORT')), web)
reactor.run()
File can be something like this:
<html>
<head><title>Test</title></head>
<body>{{ var }}</body>
</html>
Note that jinja2 rendering is a synchronous operation and it will block twisted reactor. To avoid it you can launch rendering in a thread or try to use built-in twisted templates but they do not provide many possibilities.