我正试图在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)
检索和组装页面之后,是否有方法编辑模板
执行此操作时:
…您正在读取文件的内容,但您正在丢弃它们
read()
是一个读取文件内容并返回它们的函数修复您的代码,使其实际执行您尝试执行的操作,可以实现以下目的:
……但这仍然是错误的
render_template
将包含模板的文件名而不是其内容作为其参数。所以你需要做的是用render_template_string
替换render_template
来实现这个功能但这仍然没有按照预期的方式使用烧瓶模板。模板的要点是,它们应该包含花括号中的内容,以指定应该进行哪些更改。用对
replace
的显式调用替换其中的静态字符串会绕过这一点,并执行相同操作的更原始版本您真正应该做的是更改您的模板,使其不在
<file>
内,而是在{{ file }}
内,然后您可以用以下代码替换所有凌乱的视图代码:最后,我不确定您是否需要
no_cache
,因为默认情况下视图函数不是缓存的。此外,响应上的默认状态代码为200。所以你可能只需要这个:相关问题 更多 >
编程相关推荐