I'm new to Flask and I'm trying to learn how to use it. I have a base knowledge of HTML and CSS (enough to make simple pages, not something really fancy).
So, I decided to give Flask a shot, it looks fairly simple to setup at least the basics.
For the moment I'm trying to run a local server (I'm using Windows 7,Python 3.4). Based on some instructions, I set up the project like this:
-Flask (main folder)
routes.py
/templates
template.html
home.html
welcome.html
/static
/css
/img
/js
/font (for the moment the static folder is empty, except the subfolders)
This is the structure of template.html:
<!--DOCTYPE html -->
<html>
<head>
<title>
My first Flask App
</title>
</head>
<body>
<div>
{% block content %}
{% endblock %}
</div>
</body>
</html>
home.html:
{% extends "template.html" %}
{% block content %}
<div>
<h2>Welcome to Flask!</h2>
<br />
<p>Click hereto go to the welcome page</p>
</div>
{% endblock %}
And finally, welcome.html:
{% extends "template.html" %}
{% block content %}
<h2>Sample</h2>
<p>What a nice page</p>
<p>Really nice</p>
{% endblock %}
This is the code in routes.py:
from flask import Flask,render_template
app=Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/welcome')
def welcome():
return render_template('welcome.html')
if __name__=='__main__':
app.run()
When I try to run the script, the terminal says:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
But, when I try to go to localhost:5000 on the browser, I got:
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.
More specifically, on the terminal says this:
127.0.0.1 - - [30/Jan/2016 14:45:51] "GET / HTTP/1.1" 500 -
I know a little about HTTP status code, so I know that code 500 is raised when there is some sort of error. Indeed, when i looked up for information about this problem, every page I found (included here on stackoverflow) suggests that there is some error, either in "routes.py" or in the html pages provided.
Just to be sure, I tried to run this script:
from flask import Flask
app=Flask(__name__)
#app.route('/')
def home():
return '''
<html>
<head>
<title>
My first Flask App
</title>
</head>
<body>
<div>
hello there!
</div>
</body>
</html>
'''
if __name__=='__main__':
app.run()
And this works fine, the server is booted and if I go to localhost:5000 I can see the page correctly. Indeed, on the terminal I see the status code 200, that means "all is ok", if I recall correctly.
I even tried to add more routes, by defining more functions that return the html pages as strings, and all works fine.
I even tried on those pages to use CSS, in the three forms (in line declaration, internal style sheet and external style sheet), it all works as expected.
So, for the last try, i run the original routes.py once again, this time with app.debug=True
This is the traceback that i got:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "C:\Users\Admin\pyproj\flask\routes.py", line 25, in <module>
app.run()
File "C:\Python34\Lib\site-packages\Flask-0.10.1-py3.4.egg\flask\app.py", line 777, in run
run_simple(host, port, self, **options)
File "C:\Python34\Lib\site-packages\werkzeug-0.11.3-py3.4.egg\werkzeug\serving.py", line 690, in run_simple
reloader_type)
File "C:\Python34\Lib\site-packages\werkzeug-0.11.3-py3.4.egg\werkzeug\_reloader.py", line 252, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
builtins.SystemExit: 0
Seriously, there must be something really obvious that I'm missing here: I checked all the codes countless times. To me, all seems fine: all the tags in the HTML documents are properly closed, the {%---%} syntax for the templates seems good written, the code on routes.py seems correct also. Furthermore, it generally seems that Flask is working, because if I try to return the html pages as strings written direcly in routes.py I can see and interact with the pages. What's going on?
EDIT
Based on davidism suggestion, I tried to run the script with app.run(debug=True,use_reloader=False)
And this is the traceback
Traceback (most recent call last):
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\_compat.py", line 33, in reraise
raise value
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "x-wingide-python-shell://70495568/2", line 16, in home
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\templating.py", line 127, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "C:\Python34\lib\site-packages\jinja2-2.8-py3.4.egg\jinja2\environment.py", line 851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "C:\Python34\lib\site-packages\jinja2-2.8-py3.4.egg\jinja2\environment.py", line 812, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Python34\lib\site-packages\jinja2-2.8-py3.4.egg\jinja2\environment.py", line 774, in _load_template
cache_key = self.loader.get_source(self, name)[1]
File "C:\Python34\lib\site-packages\flask-0.10.1-py3.4.egg\flask\templating.py", line 64, in get_source
raise TemplateNotFound(template)
I can see the traceback on the browser aswell.
EDIT 2:
Thanks to davidism, I tried to run the script from the command line and it works perfectly. Normally I use WingIDE for writing python code, debugging and so on; but in this particular case it seems to conflict with Jinja2. Indeed, I tested several times now, and every time I use WingIDE I get the 500 status code, when I run the script from the command line (even if I simply double-click on the script) it works fine.
Related
so I've been following this tutorial on how to build an basic Flask website off youtube Tutorial. Currently trying to add HTML templates which are giving me "500 Internal Server Error" with application errors in the CMD.
**My python code
**`
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
#app.route("/<name>")
def home(name):
return render_template("index.html", content=name)
if __name__ == "__main__":
app.run()
**my html code **
<!DOCTYPE html>
<html>
<head>
<title>ETF World!</title>
</head>
<body>
<h1>Explore the world of Exchange Traded Funds</h1>
<p>{{content}}</p>
</body>
</html>
The ERROR
Traceback (most recent call last):
File "C:\Users\Bradley J Stewart\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Bradley J Stewart\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Bradley J Stewart\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Bradley J Stewart\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
TypeError: home() missing 1 required positional argument: 'name'
I expected the website to work when I enter a forward slash in the URL and for dynamic information to pass information to be delivered from the backend to the front of what "content" variable I wrote. Not 100% sure if the video is relevant anymore as it is 3 years old
Any help is deeply appreciated.
it happens to work on mine though.
main.py
from flask import Flask, redirect, url_for, render_template
app = Flask(__name__)
#app.route("/<name>")
def home(name):
return render_template("index.html", content=name)
if __name__ == "__main__":
app.run()
index.html:
<head>
<title>ETF World!</title>
</head>
<body>
<h1>Explore the world of Exchange Traded Funds</h1>
<p>{{content}}</p>
</body>
</html>
also make sure to put index.html to the template folder because flask look into that folder.
I am using flask_babel for localization of a python project.
When extracting translatable strings from templates, which is put in {{ _('') }} , i am getting the following error. If anyone of you can solve it, please share the solution here. thanks in advance.
Traceback (most recent call last):
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2069, in __call__
return self.wsgi_app(environ, start_response)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2054, in wsgi_app
response = self.handle_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2051, in wsgi_app
response = self.full_dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1501, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1499, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1485, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/index.py", line 34, in index
return render_template_with_nav_info('main/index.html')
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/utils.py", line 60, in render_template_with_nav_info
return render_template(template, **kwargs)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 147, in render_template
return _render(
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 128, in _render
rv = template.render(context)
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 1289, in render
self.environment.handle_exception()
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 924, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 1, in top-level template code
{% extends 'layouts/base.html' %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/layouts/base.html", line 36, in top-level template code
{% block content %}{% endblock %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 5, in block 'content'
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/utils.py", line 81, in from_obj
if hasattr(obj, "jinja_pass_arg"):
jinja2.exceptions.UndefinedError: '_' is undefined
#MAIN APP FILE
from flask_login import current_user
from flask import request , Flask
from flask_babel import Babel
from .utils import render_template_with_nav_info
from .. import main
from ...models import Corpus
from ...utils.pagination import int_or
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)
#babel.localeselector
def get_locale():
#return request.accept_languages.best_match(['es', 'fr', 'en'])
return 'bo_CN'
#main.route('/')
def index():
if current_user.is_authenticated and not
current_user.is_anonymous:
corpora = Corpus.for_user(current_user, _all=False).paginate(
page=int_or(request.args.get("page"), 1),
per_page=20 # ToDo: Should it be hardcoded ?
)
return render_template_with_nav_info("main/index_loggedin.html", corpora=corpora)
return render_template_with_nav_info('main/index.html')
TEMPLATE FILE (index.html)
{% extends 'layouts/base.html' %}
{% block content %}
<div class="ui text container">
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
<p>Pyrrha is a simple Python Flask WebApp to fasten the post-correction of lemmatized and morpho-syntactic tagged corpora.</p>
<p>It is under active development at the École Nationale des Chartes and can
be found on github.</p>
<p>To cite it in a paper, please use the information available on Zenodo</p>
</div>
{% endblock %}
After applying the following codes in init.py module, its working fine. Thank you
babel = Babel(app)
#babel.localeselector
def get_locale():
return 'es'
remove the "_" in the h1 tag in the template's file
I am creating a simple app in Python 3.5.2 that authenticates users via Active Directory and applies additional rules based on a user's group membership. The app can successfully authenticate users using the win32security package, and tries to obtain group membership info using pyad.
My problem: I get a pywintypes.com_error message when running the code on my Flask app, preventing me from getting group membership info.
When I run the backend code separately on an iPython console, it works fine. I am able to query group membership. However, when it is part of a Flask app, an error pops out. I have isolated the problem to this part of the code (DN information masked):
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,
DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName")
for member in group.get_members()],[])
Has anyone encountered this before? I cannot think of why the code won't run in Flask (though I have just started learning Flask) but it will run in the console.
Code Reference:
I have 3 Python files for my Flask app and an html file in the templates folder.
run.py
from app import app
import os
app.secret_key = os.urandom(16)
app.run(debug=True)
init.py
from flask import Flask
app = Flask(__name__)
from app import views
views.py
from app import app
from flask import Flask, flash, render_template, request, session
import win32security as win32
from pyad import adgroup
#app.route("/")
def home():
if not session.get("logged_in"):
return render_template("login.html")
else:
return "You are currently logged in."
#app.route("/login", methods=["GET","POST"])
def login():
#initialize variables
username = request.form["username"]
password = request.form["password"]
DOMAIN = "test.domain.com.somecountry"
error = None
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
group_members = sum([member.get_attribute("sAMAccountName") for member in group.get_members()],[])
if username in group_members:
try:
token = win32.LogonUser(username, DOMAIN, password,
win32.LOGON32_LOGON_NETWORK,
win32.LOGON32_PROVIDER_DEFAULT)
is_auth = bool(token)
if is_auth:
session["logged_in"] = True
except:
error = "Incorrect credentials. Please try again."
else:
error = "You are not permitted to access this."
return render_template("login.html", error=error)
login.html
<!doctype html>
<title>Login Test</title>
{% block body %}
{% if session["logged_in"] %}
<p>You are currently logged in.</p>
{% else %}
<form action="/login" method="POST">
<input type="username" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Log In">
</form>
<li>{{error}}</li>
{% endif %}
{% endblock %}
This is the error traceback:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 2000, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1991, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1567, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1988, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1641, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1544, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1639, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\flask\app.py", line 1625, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\user\Documents\test\app\views.py", line 23, in login
group = adgroup.ADGroup.from_dn('CN=someCN,OU=someOU1,OU=someOU2,DC=test,DC=domain,DC=com,DC=somecountry')
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 131, in from_dn
return cls(distinguished_name, None, options)
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 88, in __init__
self.__set_adsi_obj()
File "C:\Users\user\AppData\Local\Continuum\Anaconda3\lib\site-packages\pyad\adobject.py", line 76, in __set_adsi_obj
self._ldap_adsi_obj = self.adsi_provider.getObject('', self.__ads_path)
File "<COMObject ADsNameSpaces>", line 2, in getObject
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147221020), None)
I was able to mitigate this error by running my same code in a python2 32bit environment.
Not sure if this is an option, but worth a shot.
I'm trying to make a flask app on google app engine which shows database entries on their own page.
This is a bit of my views.py code:
#app.route('/posts/<int:id>')
def display_post(id):
post = Post.filter('id =', id)
return render_template('display_post.html', post=post)
Then my display_posts.html
{% extends "base.html" %}
{% block content %}
<ul>
<h1 id="">Post</h1>
<li>
{{ posts.title }}<br />
{{ posts.content }}
</li>
</ul>
{% endblock %}
Now when I have a post with ID 5700305828184064 and visit this page I should see the title and content:
www.url.com/posts/5700305828184064
However I get this traceback:
<type 'exceptions.AttributeError'>: type object 'Post' has no attribute 'filter'
Traceback (most recent call last):
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/main.py", line 4, in <module>
run_wsgi_app(app)
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 99, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 117, in run_bare_wsgi_app
result = application(env, _start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 874, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 864, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/blog/views.py", line 25, in display_post
post = Post.filter('id =', id)
How can I show the title and content of the entry for a given ID?
You need to create a query object first, then apply the filter to that.
q = Post.all()
post = q.filter("id =", id)
This is the first example in the GAE docs on queries.
Also, your template references the name posts, but you've passed in the name post. Change your template appropriately.
I'm trying to build my first GAE app with jinja2. After overcoming a dozen small errors, now I'm stuck with this:
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1536, in __call__
rv = self.handle_exception(request, response, e)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1530, in __call__
rv = self.router.dispatch(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1278, in default_dispatcher
return route.handler_adapter(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 1102, in __call__
return handler.dispatch()
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 572, in dispatch
return self.handle_exception(e, self.app.debug)
File "C:\Program Files (x86)\Google\google_appengine\lib\webapp2\webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "C:\Users\CG\Documents\udacity\HiMon\main.py", line 31, in get
template = jinja_environment.get_template('index.html')
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 719, in get_template
return self._load_template(name, self.make_globals(globals))
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\environment.py", line 693, in _load_template
template = self.loader.load(self, name, globals)
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 115, in load
source, filename, uptodate = self.get_source(environment, name)
File "C:\Program Files (x86)\Google\google_appengine\lib\jinja2\jinja2\loaders.py", line 180, in get_source
raise TemplateNotFound(template)
TemplateNotFound: index.html
Here my yaml file:
application: himother
version: 1
runtime: python27
api_version: 1
threadsafe: yes
handlers:
- url: /favicon\.ico
static_files: favicon.ico
upload: favicon\.ico
- url: .*
script: main.app
libraries:
- name: webapp2
version: "2.5.1"
- name: jinja2
version: "2.6"
Here my code:
import os
import webapp2
import jinja2
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
class MainPage(webapp2.RequestHandler):
def get(self):
template_values = {
'name': 'Serendipo',
'verb': 'extremely happy'
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
app = webapp2.WSGIApplication([('/', MainPage)],
debug=True)
Here my .html template:
<!DOCTYPE html>
<html>
<head>
<title>Look Ma, I'm using Jinja!</title>
</head>
<body>
Hi there - I'm {{ name }}, and I {{ verb }} programming!
</body>
</html>
Despite the error message, I have a folder called "templates" and, within it, created the index.html file:
I also have installed jinja2.
Does anyone have any idea of the cause of this error now?
Try to use
loader=jinja2.FileSystemLoader('templates')
instead of
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates'))
It works for me.
This solved it for me:
mkdir templates
echo "hello world" > templates/index.html
Well, my error was simple and silly.
I have create the file "index.html" the wrong way (here the right way). So, my "index.html" file was indeed a ".text" file (because I just rename it to "index.html" instead of "save as" index.html").
Thanks for the help, guys!
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),autoescape = True)
Two thoughts based on getting my first GAE effort with Jinja2 to work. First, in your yaml file, you have "-url: ." though I used "-url: /." based on tutorials I saw. However, this may be irrelevant to your issue. Second, I used the guidance on this page for how I established my Jinja2 renderer and had no issue with the template being found in the templates subdirectory of the application directory:
http://webapp-improved.appspot.com/api/webapp2_extras/jinja2.html#module-webapp2_extras.jinja2
I received the same error and tried all answers. Later, I got to know that you first need to configure the environment with the right folder to search the html file and only then jinja2 will be able to locate the file.
Following lines will remove the error:
env = Environment(loader=FileSystemLoader(searchpath='C:\Folder\of\html\file')
template = env.get_template('Name_of_file.html')