#python #bottle #mako
#python #бутылка #мако
Вопрос:
Есть ли способ в бутылке, где я могу установить Mako в качестве средства визуализации шаблонов по умолчанию.
Это код, который я хотел выполнить:
app.route(path='/', method='GET', callback=func, apply=[auth], template='index.html')
Где:
func : a function that returns a value (a dict)
auth : is a decorator for authentication
index.html : displays the values from the "func" and contains "Mako" syntax
Я пытался:
- Изменение .html на .mako
- Использовал
renderer
плагин :app.route(..., renderer='mako'
) - Пробовал разные шаблоны:
# even used '.mako', 'index.mako', 'index.html.mako'
Также заглянул внутрь bottle
объекта, но не увидел никаких намеков на установку / изменение движка по умолчанию:
# Print objects that contains "template" keyword, the object itself, and its value
for i in dir(app):
if 'template' in i.lower():
print '{}: {}'.format(i, getattr(app, i))
Ответ №1:
Вы можете вернуть шаблон Mako из своей функции route:
from bottle import mako_template as template
def func():
...
return template('mytemplate.mako')
Редактировать:
bottle.mako_view
может быть то, что вы ищете. Сам еще не пробовал, но что-то вроде этого может помочь:
app.route(path='/', method='GET', callback=func, apply=[auth, mako_view('index.html')])
Комментарии:
1. Спасибо, Рон, но такой подход возможен только в том случае, если я возвращаю значения w / Mako в самом
callback
себе. То, что я делаю, имитирует то, как django использует urls.py , только то, что в этом случае я, похоже, не могу сказать bottle использовать Mako вместо встроенного шаблона для возврата представления.2. А, понятно. Возможно
mako_view
, это то, что вы ищете? Ответ обновлен. Надеюсь, это поможет!3. Потрясающий Рон! не понял, что mako_view также можно использовать в фильтре применения 🙂 Принял это как ответ (y)
Ответ №2:
Как кажется, в настоящее время нет способа изменить шаблон по умолчанию на что-то другое, поэтому в итоге было найдено временное решение (до тех пор, пока не появится что-то встроенное для bottle — или пока оно не будет найдено).
Вот временное решение :
import bottle as app
# Suppose this is the function to be used by the route:
def index(name):
data = 'Hello {}!'.format(name)
return locals()
# This was the solution (decorator).
# Alter the existing function which returns the same value but using mako template:
def alter_function(func, file_):
def wrapper(*args, **kwargs):
data = func(*args, **kwargs)
return app.mako_template(file_, **data)
return wrapper
# This really is the reason why there became a complexity:
urls = [
# Format: (path, callback, template, apply, method)
# Note: apply and method are both optional
('/<name>', index, 'index')
]
# These are the only key names we need in the route:
keys = ['path', 'callback', 'template', 'apply', 'method']
# This is on a separate function, but taken out anyway for a more quick code flow:
for url in urls:
pairs = zip(keys, url)
set_ = {}
for key, value in pairs:
set_.update({key:value})
callback = set_.get('callback')
template = set_.get('template')
set_['callback'] = alter_function(callback, template)
app.route(**set_)
app.run()
Ответ №3:
import bottle
from bottle import(
route,
mako_view as view, #THIS IS SO THAT @view uses mako
request,
hook,
static_file,
redirect
)
from bottle import mako_template as template #use mako template
@route("/example1")
def html_example1(name="WOW"):
return template("<h1>Hello ${name}</h1>", name=name)
@route("/example2")
@view("example2.tpl")
def html_exampl2(name="WOW"):
#example2.tpl contains html and mako template code like: <h1>${name}</h1>
return {"name" : name}