Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask doesn't locate template directory when running with twisted

Following some advice that I found here I am trying to use Flask as a web interface for an application that runs with twisted.

As suggested in Flask documentation I created a "templates" directory which is at the same level as my script but when I launch the server I get the following error:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

When I do not try to load a template and just write a string in the request it works fine. This is what makes me think it is related to the load of the template.

from twisted.internet import reactor
from twisted.web.resource import Resource
from twisted.web.wsgi import WSGIResource
from twisted.internet.threads import deferToThread
from twisted.web.server import Site, NOT_DONE_YET

from flask import Flask, request, session, redirect, url_for, abort, \ 
render_template, flash

app= Flask(__name__)
app.config.from_object(__name__)

@app.route('/login', methods= ['GET', 'POST'])
def login():
    return render_template('login.html', error= error)

if __name__ == '__main__':
    root = WSGIResource(reactor, reactor.getThreadPool(), app)
    factory = Site(root)
    reactor.listenTCP(8880, factory)
    reactor.run()
like image 716
dry Avatar asked Dec 12 '11 17:12

dry


2 Answers

Some frameworks will change directory from your current working directory when they are run in daemon mode, and this might very well be the case here.

Flask, since 0.7, has supported passing a template_folder keyword argument when calling Flask, so you could try:

import os
tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')

The following is a shorter version that will work just fine:

tmpl_dir = os.path.join(os.path.dirname(__file__), 'templates)
# ...
app = Flask('myapp', template_folder=tmpl_dir)
like image 143
dskinner Avatar answered Sep 30 '22 19:09

dskinner


You can feed Jinja2 with a default templates directory (as written here) like this :

import jinja2

app = Flask(__name__)
app.jinja_loader = jinja2.FileSystemLoader('path/to/templates/directory')
like image 38
Kevin Avatar answered Sep 30 '22 21:09

Kevin