Python 瓶子:使用jinja2_视图装饰器

Python 瓶子:使用jinja2_视图装饰器,python,jinja2,bottle,python-decorators,Python,Jinja2,Bottle,Python Decorators,如果我直接从瓶子中导入post、get和jinja2_视图,我就可以使用jinja2_视图作为装饰器: from bottle import get, post, request, run, jinja2_view @jinja2_view('index.html') @get('/') def index(): return run(host='localhost', port=8080, debug=True, reloader=True) 但是如果我导入并使用battle()

如果我直接从瓶子中导入post、get和jinja2_视图,我就可以使用jinja2_视图作为装饰器:

from bottle import get, post, request, run, jinja2_view

@jinja2_view('index.html')
@get('/')
def index():
    return

run(host='localhost', port=8080, debug=True, reloader=True)
但是如果我导入并使用
battle()
构造函数,我就不能再使用jinja装饰器了:

from bottle import Bottle, get, post, request, run, jinja2_view

app = Bottle()

@app.jinja2_view('index.html')
@app.get('/')
def index():
    return

run(app, host='localhost', port=8080, debug=True, reloader=True)
我得到:

Traceback (most recent call last):
  File "webserver.py", line 10, in <module>
    @app.jinja2_view('index.html')
AttributeError: 'Bottle' object has no attribute 'jinja2_view'
例外情况:

TypeError('get_now() takes exactly 1 argument (0 given)',)

如果我将
@jinja2_视图('now.html')
注释掉,则路由将工作并返回正确的json响应。

您不能这样做,因为正如错误所述,该类没有属性
jinja2_视图
。但是,如果您同时使用这两个视图,则没有问题,每一个都是为了它的目的:
battle()
来实例化您的应用程序,而
jinja2_视图
来呈现模板。

jinja2_视图
是瓶子模块提供的函数,它不是
battle
类的类方法。 因此,当您调用
@app.jinja2_视图
时,python会搜索
app
(这是
battle.battle
的一个实例)一个名为jinja2_视图的属性,它显然找不到该属性

因此,您有两个非常简单的选项来纠正此问题:

  • 您可以返回使用
    @jinja2\u视图('index.html')
  • 只需导入瓶子并对所有瓶子方法使用完全限定的名称空间,例如
    @bottle.jinja2_view('index.html')
    app=bottle.bottle()
  • 我个人非常喜欢后者,因为它避免了对全局名称空间的意外污染,这一点很重要,因为这些围绕Web服务器构建的小项目往往会随着时间的推移而增长和膨胀。当然,您的里程数可能会有所不同

    编辑 我根据你的原著创建了一个更简单的示例,希望这将有助于确定问题所在。尝试运行以下命令:

    from bottle import get, run, jinja2_view, Bottle
    import datetime
    
    app = Bottle()
    @app.get('/now')
    @jinja2_view('now.html')
    def get_now():
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return { 'now': now }
    
    run(app, host='localhost', port=8080, debug=True)
    

    在浏览器中查看此项将在
    元素中正确呈现日期时间字符串。如果它也适用于您,那么问题可能出在插件上。

    我添加了一个代码段来说明为什么在edit 1中不起作用,我添加了一个代码段来说明为什么在edit 1中不起作用,这是因为在您的代码段中,您已将
    jinja2\u视图
    装饰器放置在路由装饰器下方。路由装饰器应该是路由处理程序def之前的最后一件事。只要颠倒它们的顺序,你的例子就可以了。当我颠倒顺序时,jinja2模板不会被呈现。它被忽略了,我得到了一个空白屏幕。你能给我看看你的
    now.html
    模板是什么样子吗?
    {{now}
    请查看下面我的答案中关于你的编辑的评论。
    from bottle import get, run, jinja2_view, Bottle
    import datetime
    
    app = Bottle()
    @app.get('/now')
    @jinja2_view('now.html')
    def get_now():
        now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return { 'now': now }
    
    run(app, host='localhost', port=8080, debug=True)