benselme / flask-mako Goto Github PK
View Code? Open in Web Editor NEWProvides support for Mako Templates in Flask.
Provides support for Mako Templates in Flask.
Was getting this error while trying to integrate Babel into my application.
If you change line 35 in flask_mako.py from:
_BABEL_IMPORTS = 'from flaskext.babel import gettext as _, ngettext, ' \
'pgettext, npgettext'
to:
_BABEL_IMPORTS = 'from flask.ext.babel import gettext as _, ngettext, ' \
'pgettext, npgettext'
it works. You'd have to check what Flask version you're running and change the import based on that.
More info: http://flask.pocoo.org/docs/extensions/
The submodule werkzeug.debug.tbtools
as of version 2.0 upwards no longer has the classes Frame
, Traceback
, Line
, therefore this line fails:
from werkzeug.debug.tbtools import Traceback, Frame, Line
# ImportError: cannot import name 'Traceback' from 'werkzeug.debug.tbtools'
Rolling back to werkzeug==2.0
crashes flask.
werkzeug has DebugFrameSummary
, DebugTraceback
and a smattering of variable for line as far I can tell. cf.werkzeug.debug.tbtools as they do not look the same I did not do a monkeypatch as working around the error reporting is not an issue for me as I can happily blank out the error catching in my internal production app.
I see in setup.py
the project status is Development Status :: 3 - Alpha
, so wanted to ask if it's actually Development Status :: 7 - Inactive
— the werkzeug
change happened over a year ago.
Docs states, that TemplateError class provides the original raised traceback as a RichTraceback() in .tb attribute. Which isn't the case anymore for flask-mako 0.3.
Is it planned to provide the original traceback again in TemplateError?
Hello,
I have some Mako issues with Flask.
When I launch my 'run' I have this error :" ImportError: No module named 'flask.ext' "
This is my app and 3 .py file to run it :
the init.py file should init app =
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os, pickle
from flask import Flask, request, current_app
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_mako import MakoTemplates
from flask_babel import Babel, lazy_gettext as _l
from config import Config
from elasticsearch import Elasticsearch
from redis import Redis
import rq
from .admin import Admin
db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
login.login_view = 'auth.login'
login.login_message = _l('Please log in to access this page.')
mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
babel = Babel()
Mako = MakoTemplates()
admin = Admin()
def create_app(config_class=Config):
app = Flask(__name__)
app.config.from_object(config_class)
Mako.init_app(app)
db.init_app(app)
migrate.init_app(app, db)
login.init_app(app)
mail.init_app(app)
bootstrap.init_app(app)
moment.init_app(app)
babel.init_app(app)
app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
if app.config['ELASTICSEARCH_URL'] else None
app.redis = Redis.from_url(app.config['REDIS_URL'])
app.task_queue = rq.Queue('microblog-tasks', connection=app.redis)
admin.init_app(app)
from app.errors import bp as errors_bp
app.register_blueprint(errors_bp)
from app.auth import bp as auth_bp
app.register_blueprint(auth_bp, url_prefix='/auth')
from app.main import bp as main_bp
app.register_blueprint(main_bp)
if not app.debug and not app.testing:
if app.config['MAIL_SERVER']:
auth = None
if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
auth = (app.config['MAIL_USERNAME'],
app.config['MAIL_PASSWORD'])
secure = None
if app.config['MAIL_USE_TLS']:
secure = ()
mail_handler = SMTPHandler(
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
fromaddr='no-reply@' + app.config['MAIL_SERVER'],
toaddrs=app.config['ADMINS'], subject='Microblog Failure',
credentials=auth, secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/microblog.log',
maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('Microblog startup')
return app
from app import models
this is the init for Views.py, this should run templates =
import os, pickle
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, g, \
jsonify, current_app
from flask_mako import render_template as m
from flask_login import current_user, login_required
from flask_babel import _, get_locale
from guess_language import guess_language
from app import db
from app.main.forms import EditProfileForm, DashForm, SearchForm, MessageForm, CustomBoard
from app.models import User, Dash, Message, Notification, Machine, DashOne
from app.main import bp
@bp.route('/mako')
@login_required
def hello_mako():
return m('hello.html', name='mako')
this is a simple Mako template hello.html =
<%inherit file="base.html"/>
<%
rows = [[v for v in range(0,10)] for row in range(0,10)]
%>
<table>
% for row in rows:
${makerow(row)}
% endfor
</table>
<%def name="makerow(row)">
<tr>
% for name in row:
<td>${name}</td>\
% endfor
</tr>
</%def>
Thanks for your help. I hope some people can help me.
Get this traceback when using _() in a mako template (test app below):
File "/home/env/lib/python2.7/site-packages/jinja2/ext.py", line 132, in _gettext_alias
return __context.call(__context.resolve('gettext'), *args, **kwargs)
AttributeError: 'str' object has no attribute 'call'
from flask_mako import MakoTemplates, render_template_string
from flask import Flask
from flask_babel import Babel
app = Flask(__name__)
app.config['MAKO_TRANSLATE_EXCEPTIONS'] = False
mako = MakoTemplates(app)
babel = Babel(app)
@app.route('/')
def index():
return render_template_string('${_("whatever")}')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=4000, debug=True)
Currently, all mako exceptions are intercepted and wrapped by the TemplateError.
This is not too useful as the mako error messages are suppressed and the stack trace is not provided in an easily readable presentation.
Template errors will typically be dumped onto the browser to allow easy navigation of the call stack
Expose the underlying Mako errors as a callableTemplateError returning the stack trace as HTML.
Changes are shown below, with the extra imports
from flask.helpers import make_response
from mako.exceptions import html_error_template
class TemplateError(RuntimeError):
""" A template has thrown an error during rendering. """
def __init__(self, template):
self.tb = RichTraceback()
self.text = text_error_template().render()
self.html = html_error_template().render()
msg = "Error occurred while rendering template '{0}'"
msg = msg.format(template.uri)
super(TemplateError, self).__init__(msg)
def __call__(self, environ, start_response):
"""Call the exception as WSGI application.
:param environ: the WSGI environment.
:param start_response: the response callable provided by the WSGI
server.
"""
response = make_response(self.html)
return response(environ, start_response)
Traceback (most recent call last):
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/zcarterc/Documents/Code/dndapp/appw.py", line 20, in simplelayout
return render_template(simplelayouts.get(url))
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/flask_mako.py", line 153, in render_template
return _render(_lookup(ctx.app).get_template(template_name),
File "/home/zcarterc/.config/python/envs/pyramid/lib/python2.7/site-packages/mako/lookup.py", line 236, in get_template
u = re.sub(r'^\/+', '', uri)
File "/usr/lib64/python2.7/re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer```
Using version 0.3, for this statement:
${field(**dict(kwargs, **{'data-type': field.type}))}
I get the following traceback:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python27\lib\site-packages\werkzeug\wsgi.py", line 639, in __call__
return app(environ, start_response)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Program Files (x86)\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\Dev\python\site-packages\rfw\frontend\blueprints\user\__init__.py", line 43, in login
return render('/form.mako', form=form, submit=u'Abrir sesión')
File "C:\Program Files (x86)\Python27\lib\site-packages\flask_mako.py", line 232, in render_template
context, ctx.app)
File "C:\Program Files (x86)\Python27\lib\site-packages\flask_mako.py", line 217, in _render
raise translated
TemplateError
translated.text contains:
\n\nTraceback (most recent call last):\n File "C:\\Program Files (x86)\\Python27\\lib\\site-packages\\flask_mako.py", line 210, in _render\n rv = template.render(**context)\n File "C:\\Program Files (x86)\\Python27\\lib\\site-packages\\mako\\template.py", line 443, in render\n return runtime._render(self, self.callable_, args, data)\n File "C:\\Program Files (x86)\\Python27\\lib\\site-packages\\mako\\runtime.py", line 807, in _render\n **_kwargs_for_callable(callable_, data))\n File "C:\\Program Files (x86)\\Python27\\lib\\site-packages\\mako\\runtime.py", line 839, in _render_context\n _exec_template(inherit, lclcontext, args=args, kwargs=kwargs)\n File "C:\\Program Files (x86)\\Python27\\lib\\site-packages\\mako\\runtime.py", line 865, in _exec_template\n callable_(context, *args, **kwargs)\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/layout.mako", line 64, in render_body\n </ul>\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/form.mako", line 4, in render_content\n ${self.h.render_form(form, context.get('submit', 'Guardar'))}\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/helpers.mako", line 248, in render_render_form\n ${render_field(field, inline=inline, **kw)}\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/helpers.mako", line 42, in render_field\n </tr>\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/helpers.mako", line 158, in render_render_field\n ${render_input(field, enclosed=enclosed if not inline else False, inline=inline, **kwargs)}\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/helpers.mako", line 138, in render_input\n <%def name="render_input_bottom(field)">\n File "D:\\Dev\\python\\site-packages\\rfw\\frontend\\templates/helpers.mako", line 146, in render_render_input\n ${field(**dict(kwargs, **{'data-type': field.type}))}\nTypeError: <lambda>() takes exactly 0 arguments (2 given)\n
If I change the statement to something like this it works:
${field(**kwargs)}
field is a WTForms form field. I've reverted back to 0.2 and all is working fine.
This variable is no longer available from a mako template since a change in how Flask manages it (pallets/flask@f34c028).
In the meantime I'm using a context_processor which helps me get around this issue:
from flask import Flask
app = Flask(__name__)
@app.context_processor
def inject_config():
return {'config': app.config}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.