动态页面内容

2024-10-02 16:23:41 发布

您现在位置: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)检索和组装页面之后,是否有方法编辑模板


Tags: 代码comappflasksearchhtml动态template
1条回答
网友
1楼 · 发布于 2024-10-02 16:23:41

执行此操作时:

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_string替换render_template来实现这个功能

@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

但这仍然没有按照预期的方式使用烧瓶模板。模板的要点是,它们应该包含花括号中的内容,以指定应该进行哪些更改。用对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")

相关问题 更多 >