烧瓶动态页面内容

时间:2020-11-05 14:05:05

标签: python

我试图在我的pythonanywhere.com免费托管上使用Flask在Python中编写动态页面。我有以下代码,希望我可以写到resp变量来创建页面。

@app.route('/xdcc-search/search.html')
def search_app():
    try:
        with open('templates/xdcc-search/search.html', 'r') as dynamic:
            dynamic.read()
    except:
        pass
    dynamic.replace("<file>","MY_FILENAME.tar")
    resp = make_response(render_template(dynamic), 200)
    no_cache(resp)
    return resp

我收到一条错误消息,指出在分配之前已引用了dynamic。在render_template(filename)检索并组合页面之后,是否可以编辑模板?

1 个答案:

答案 0 :(得分:0)

执行此操作时:

with open('templates/xdcc-search/search.html', 'r') as dynamic:
    dynamic.read()

...您正在读取文件的内容,但是却将它们丢弃了-read()是一个读取文件内容并返回它们的函数。

修复您的代码,使其真正执行您要执行的操作即可:

@app.route('/xdcc-search/search.html')
def search_app():
    try:
        with open('templates/xdcc-search/search.html', 'r') as dynamic:
            contents = dynamic.read()
    except:
        pass
    contents.replace("<file>","MY_FILENAME.tar")
    resp = make_response(render_template(contents), 200)
    no_cache(resp)
    return resp

...但是那仍然是错误的; render_template将包含模板的文件名(而不是其内容)作为其参数。因此,您需要做的就是将render_template替换为render_template_string

@app.route('/xdcc-search/search.html')
def search_app():
    try:
        with open('templates/xdcc-search/search.html', 'r') as dynamic:
            contents = dynamic.read()
    except:
        pass
    contents.replace("<file>","MY_FILENAME.tar")
    resp = make_response(render_template_string(contents), 200)
    no_cache(resp)
    return resp

但是,这仍然没有使用Flask模板。模板的要点是它们应包含在大括号中,以指定应进行哪些更改。通过显式调用replace来替换其中的静态字符串会绕过它,并且会做同样事情的更原始的版本。

您真正要做的是更改模板,以使其内部没有<file>,而是拥有{{ file }},然后可以替换所有模板混乱的视图代码与此:

@app.route('/xdcc-search/search.html')
def search_app():
    resp = make_response(render_template("xdcc-search/search.html", file="MY_FILENAME.tar"), 200)
    no_cache(resp)
    return resp

最后,我不确定您是否需要no_cache,因为默认情况下不缓存视图函数。另外,响应的默认状态码是200。因此,您可能需要的就是这样:

@app.route('/xdcc-search/search.html')
def search_app():
    return render_template("xdcc-search/search.html", file="MY_FILENAME.tar")