Reputation: 31
I have some templates on an FTP server, and my app is running on another server. Can I use render_template
to render a template at an FTP link?
Upvotes: 2
Views: 622
Reputation: 168856
Yes, one can use render_template()
function with the template files on another server. Create a loader that gets the remote template from the link. In this example, I use an HTTP server, but you can use an FTP server by changing the URL passed to the UrlLoader constructor.
from flask import Flask, render_template
from jinja2 import BaseLoader, TemplateNotFound
from urllib import urlopen
from urlparse import urljoin
class UrlLoader(BaseLoader):
def __init__(self, url_prefix):
self.url_prefix = url_prefix
def get_source(self, environment, template):
url = urljoin(self.url_prefix, template)
try:
t = urlopen(url)
if t.getcode() is None or t.getcode() == 200:
return t.read().decode('utf-8'), None, None
except IOError:
pass
raise TemplateNotFound(template)
app = Flask(__name__)
app.jinja_loader = UrlLoader('http://localhost:8000/')
@app.route('/')
def root():
return render_template('hello.html')
if __name__ == "__main__":
app.run(debug=True)
Upvotes: 4